Inheritance: System.CodeDom.CodeExpression
Exemplo n.º 1
0
	public void EmitImplementationCode (CodeTypeDeclaration ctd) 
	{
	    byte[] bytes = Hash;
	    int hash = 0;
	    
	    for (int i = 0; bytes.Length - i > 3; i += 4)
		hash ^= BitConverter.ToInt32 (bytes, i);
	    
	    // Insane Clown Property
	    
	    CodeMemberProperty icp = new CodeMemberProperty ();
	    icp.Name = "ImplementationCode";
	    icp.Attributes = MemberAttributes.Family | MemberAttributes.Override;
	    icp.Type = new CodeTypeReference (typeof (int));
	    icp.HasGet = true;
	    icp.HasSet = false;
	    
	    // get { return base.ImplementationCode ^ [number] } 
	    // becomes:
	    // get { return LameCodeDomXor (base.ImplementationCode, [number]); }
	    
	    CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
	    invoke.Method = new CodeMethodReferenceExpression (CDH.This, "LameCodeDomXor");
	    invoke.Parameters.Add (new CodePropertyReferenceExpression (CDH.Base, "ImplementationCode"));
	    invoke.Parameters.Add (new CodePrimitiveExpression (hash));
	    
	    icp.GetStatements.Add (new CodeMethodReturnStatement (invoke));

	    ctd.Members.Add (icp);
	}
Exemplo n.º 2
0
	public void EmitGetFingerprint (CodeTypeDeclaration ctd)
	{
	    byte[] hash = Hash;
	    
	    CodeArrayCreateExpression mkdata = new CodeArrayCreateExpression (CDH.Byte, hash.Length);
	    
	    for (int i = 0; i < hash.Length; i++)
		// well, this for loop sucks
		mkdata.Initializers.Add (new CodePrimitiveExpression (hash[i]));
	    
	    CodeMemberMethod m = new CodeMemberMethod ();
	    m.Name = "GetFingerprint";
	    m.Attributes = MemberAttributes.Public | MemberAttributes.Override;
	    m.ReturnType = CDH.Fingerprint;
	    m.Parameters.Add (CDH.Param (CDH.IContext, "unused1"));
	    m.Parameters.Add (CDH.Param (CDH.Fingerprint, "unused2"));
			
	    CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
	    invoke.Method = new CodeMethodReferenceExpression (Generic, "Constant");
	    invoke.Parameters.Add (mkdata);
	    
	    m.Statements.Add (new CodeMethodReturnStatement (invoke));
	    
	    ctd.Members.Add (m);
	}
        internal static void BuildEvalExpression(string field, string formatString, string propertyName,
            Type propertyType, ControlBuilder controlBuilder, CodeStatementCollection methodStatements, CodeStatementCollection statements, CodeLinePragma linePragma, bool isEncoded, ref bool hasTempObject) {

            // Altogether, this function will create a statement that looks like this:
            // if (this.Page.GetDataItem() != null) {
            //     target.{{propName}} = ({{propType}}) this.Eval(fieldName, formatString);
            // }

            //     this.Eval(fieldName, formatString)
            CodeMethodInvokeExpression evalExpr = new CodeMethodInvokeExpression();
            evalExpr.Method.TargetObject = new CodeThisReferenceExpression();
            evalExpr.Method.MethodName = EvalMethodName;
            evalExpr.Parameters.Add(new CodePrimitiveExpression(field));
            if (!String.IsNullOrEmpty(formatString)) {
                evalExpr.Parameters.Add(new CodePrimitiveExpression(formatString));
            }

            CodeStatementCollection evalStatements = new CodeStatementCollection();
            BuildPropertySetExpression(evalExpr, propertyName, propertyType, controlBuilder, methodStatements, evalStatements, linePragma, isEncoded, ref hasTempObject);

            // if (this.Page.GetDataItem() != null)
            CodeMethodInvokeExpression getDataItemExpr = new CodeMethodInvokeExpression();
            getDataItemExpr.Method.TargetObject = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Page");
            getDataItemExpr.Method.MethodName = GetDataItemMethodName;

            CodeConditionStatement ifStmt = new CodeConditionStatement();
            ifStmt.Condition = new CodeBinaryOperatorExpression(getDataItemExpr, 
                                                                CodeBinaryOperatorType.IdentityInequality, 
                                                                new CodePrimitiveExpression(null));
            ifStmt.TrueStatements.AddRange(evalStatements);
            statements.Add(ifStmt);
        }
        public void Visit(GetDatePrimitive primitive)
        {
            var expression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("PrimitiveFunctions"), "GetDate");

            _codeStack.Peek().Scope = new ScopeData<Type> { Type = typeof(DateTime), CodeDomReference = new CodeTypeReference(typeof(DateTime)) };
            _codeStack.Peek().CodeExpression = expression;
        }
 private void AddPropertyGroup(AssemblyBuilder assemblyBuilder, string groupName, string propertyNames, Hashtable properties, CodeTypeDeclaration type, CodeNamespace ns)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Name = groupName,
         Attributes = MemberAttributes.Public,
         HasGet = true,
         Type = new CodeTypeReference("ProfileGroup" + groupName)
     };
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = { TargetObject = new CodeThisReferenceExpression(), MethodName = "GetProfileGroup" }
     };
     expression.Parameters.Add(new CodePrimitiveExpression(property.Name));
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(new CodeCastExpression(property.Type, expression));
     property.GetStatements.Add(statement);
     type.Members.Add(property);
     CodeTypeDeclaration declaration = new CodeTypeDeclaration {
         Name = "ProfileGroup" + groupName
     };
     declaration.BaseTypes.Add(new CodeTypeReference(typeof(ProfileGroupBase)));
     foreach (string str in propertyNames.Split(new char[] { ';' }))
     {
         this.CreateCodeForProperty(assemblyBuilder, declaration, (ProfileNameTypeStruct) properties[str]);
     }
     ns.Types.Add(declaration);
 }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     object obj2 = ((CodeDomSerializer) manager.GetSerializer(typeof(ImageList).BaseType, typeof(CodeDomSerializer))).Serialize(manager, value);
     ImageList list = value as ImageList;
     if (list != null)
     {
         StringCollection keys = list.Images.Keys;
         if (!(obj2 is CodeStatementCollection))
         {
             return obj2;
         }
         CodeExpression targetObject = base.GetExpression(manager, value);
         if (targetObject == null)
         {
             return obj2;
         }
         CodeExpression expression2 = new CodePropertyReferenceExpression(targetObject, "Images");
         if (expression2 == null)
         {
             return obj2;
         }
         for (int i = 0; i < keys.Count; i++)
         {
             if ((keys[i] != null) || (keys[i].Length != 0))
             {
                 CodeMethodInvokeExpression expression3 = new CodeMethodInvokeExpression(expression2, "SetKeyName", new CodeExpression[] { new CodePrimitiveExpression(i), new CodePrimitiveExpression(keys[i]) });
                 ((CodeStatementCollection) obj2).Add(expression3);
             }
         }
     }
     return obj2;
 }
        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;
            }
        }
Exemplo n.º 8
0
		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);
		}
        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;
            }
        }
Exemplo n.º 10
0
        static void AddEntryPoint()
        {
            CodeEntryPointMethod start = new CodeEntryPointMethod();
            CodeObjectCreateExpression objectCreate =
                new CodeObjectCreateExpression(
                new CodeTypeReference("CodeDOMCreatedClass"),
                new CodePrimitiveExpression(5.3),
                new CodePrimitiveExpression(6.9));

            // Add the statement:
            // "CodeDOMCreatedClass testClass =
            //     new CodeDOMCreatedClass(5.3, 6.9);"
            start.Statements.Add(new CodeVariableDeclarationStatement(
                new CodeTypeReference("CodeDOMCreatedClass"), "testClass",
                objectCreate));

            // Creat the expression:
            // "testClass.ToString()"
            CodeMethodInvokeExpression toStringInvoke =
                new CodeMethodInvokeExpression(
                new CodeVariableReferenceExpression("testClass"), "ToString");

            // Add a System.Console.WriteLine statement with the previous
            // expression as a parameter.
            start.Statements.Add(new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("System.Console"),
                "WriteLine", toStringInvoke));
            targetClass.Members.Add(start);
        }
Exemplo n.º 11
0
        public override void WriteCode(ISequenceVisitor visitor, TemplateContext ctx)
        {
            //base.WriteCode(ctx);
            var handlerMethod = ctx.CurrentDeclaration.protected_virtual_func(typeof(void), Name, Name.ToLower());
            var handlerInvoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), Name);

            foreach (CodeParameterDeclarationExpression item in ctx.CurrentMethod.Parameters)
            {
                handlerMethod.Parameters.Add(item);
                handlerInvoke.Parameters.Add(new CodeVariableReferenceExpression(item.Name));
            }

            //foreach (var item in AllContextVariables)
            //{
            //    if (item.IsSubVariable) continue;
            //    var type = item.SourceVariable == null ? item.Name : item.SourceVariable.RelatedTypeName;
                
                
            //    handlerMethod.Parameters.Add(new CodeParameterDeclarationExpression(
            //       type , item.AsParameter));
            //    handlerInvoke.Parameters.Add(new CodeVariableReferenceExpression(item.ToString()));
            //}
            ctx.CurrentStatements.Add(handlerInvoke);
            //ctx.PushStatements(handlerMethod.Statements);

            //ctx.PopStatements();
        }
Exemplo n.º 12
0
        public void GenerateBuildCode(GeneratorContext ctx)
        {
            string varName = ctx.NewId ();
            CodeVariableDeclarationStatement varDec = new CodeVariableDeclarationStatement (typeof(Gtk.IconFactory), varName);
            varDec.InitExpression = new CodeObjectCreateExpression (typeof(Gtk.IconFactory));
            ctx.Statements.Add (varDec);

            CodeVariableReferenceExpression var = new CodeVariableReferenceExpression (varName);
            foreach (ProjectIconSet icon in icons) {

                CodeExpression exp = new CodeMethodInvokeExpression (
                    var,
                    "Add",
                    new CodePrimitiveExpression (icon.Name),
                    icon.GenerateObjectBuild (ctx)
                );
                ctx.Statements.Add (exp);
            }

            CodeExpression addd = new CodeMethodInvokeExpression (
                var,
                "AddDefault"
            );
            ctx.Statements.Add (addd);
        }
		CodeMemberMethod CreateMethod()
		{
			CodeMemberMethod method = new CodeMemberMethod();
			
			// BeginInit method call.
			CodeExpressionStatement statement = new CodeExpressionStatement();
			CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression();
			statement.Expression = methodInvoke;
			
			CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression();
			methodRef.MethodName = "BeginInit";
			
			CodeCastExpression cast = new CodeCastExpression();
			cast.TargetType = new CodeTypeReference();
			cast.TargetType.BaseType = "System.ComponentModel.ISupportInitialize";
			
			CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression();
			fieldRef.FieldName = "pictureBox1";
			fieldRef.TargetObject = new CodeThisReferenceExpression();
			cast.Expression = fieldRef;

			methodRef.TargetObject = cast;
			methodInvoke.Method = methodRef;

			method.Statements.Add(statement);
			return method;
		}
        private CodeMemberMethod DownloadImpl(AstNode statement, string methodName, CodeTypeReference returnType, int line)
        {
            var statementDomArg = VisitChild(statement);

            if(statementDomArg.Scope.CodeDomReference.BaseType == typeof(Table<>).Name)
            {
                if (statementDomArg.Tag != null)
                    ((Action)statementDomArg.Tag)(); //remove call to OnSelect
            }
            else if( statementDomArg.Scope.CodeDomReference.BaseType != typeof(string).FullName)
                Errors.Add(new DownloadRequireString(new Semantic.LineInfo(statement.Line.Line, statement.Line.CharacterPosition)));

            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "Download_" + statementDomArg.MethodIdentifier;
            method.Attributes = MemberAttributes.Private;
            method.ReturnType = returnType;
            GenerateCallStatement(method.Statements, line);

            method.Statements.Add(new CodeMethodReturnStatement(
             new CodeMethodInvokeExpression(
                 new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("Http"), methodName), new CodeThisReferenceExpression(),
                 statementDomArg.CodeExpression, new CodePrimitiveExpression(line))));

            _mainType.Type.Members.Add(method);

            var methodcall = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(null, method.Name));

            _codeStack.Peek().CodeExpression = methodcall;
            return method;
        }
 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;
 }
        public void Visit(TakeTextStatement statement)
        {
            var expression = new CodeMethodInvokeExpression();
            expression.Method.MethodName = "TakeText";

            _codeStack.Peek().CodeExpression = expression;
        }
        public void Run()
        {
            var compileUnit = new CodeCompileUnit();
            var myNamespace = new CodeNamespace("MyNamespace");
            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            var myClass = new CodeTypeDeclaration("MyClass");
            var start = new CodeEntryPointMethod();
            var cs1 = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Console"),
                "WriteLine", new CodePrimitiveExpression("Hello World!"));

            compileUnit.Namespaces.Add(myNamespace);
            myNamespace.Types.Add(myClass);
            myClass.Members.Add(start);
            start.Statements.Add(cs1);

            var provider = new CSharpCodeProvider();

            using (var sw = new StreamWriter("HelloWorld.cs", false))
            {
                var tw = new IndentedTextWriter(sw, "    ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw,
                    new CodeGeneratorOptions());
                tw.Close();
            }
        }
Exemplo n.º 18
0
        public void Visit(PickStatement statement)
        {
            VerifyCssSelector(statement.Selector, new Semantic.LineInfo(statement.Line.Line, statement.Line.CharacterPosition));

            _codeStack.Peek()
                .ParentStatements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("result"),
                    "AddColumn",
                    new CodePrimitiveExpression(statement.Selector)));

            var expression = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("node"),
                "Pick",
                new CodePrimitiveExpression(statement.Selector)
                );

            var takeDomArg = VisitChild(statement.TakeStatement);
            var takeExpression = takeDomArg.CodeExpression as CodeMethodInvokeExpression;
            takeExpression.Method.TargetObject = expression;

            if (statement.Match != null && statement.Match.Replace != null)
            {
                takeExpression = new CodeMethodInvokeExpression(takeExpression, "MatchReplace", new CodePrimitiveExpression(statement.Match.Value), new CodePrimitiveExpression(statement.Match.Replace.Value));
            }
            else if (statement.Match != null)
            {
                takeExpression = new CodeMethodInvokeExpression(takeExpression, "Match", new CodePrimitiveExpression(statement.Match.Value));
            }

            _codeStack.Peek().Tag = true;
            _codeStack.Peek().CodeExpression = takeExpression;
            _codeStack.Peek().Scope = new ScopeData<Type> { Type = typeof(string), CodeDomReference = new CodeTypeReference(typeof(string)) };
        }
        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;
            }
        }
 internal CodeStatement GetCodeStatement(BaseTemplateCodeDomTreeGenerator generator, CodeExpression ctrlRefExpr)
 {
     CodeExpression expression2;
     if (this.UseSetAttribute)
     {
         CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IAttributeAccessor), ctrlRefExpr), "SetAttribute", new CodeExpression[0]);
         expression.Parameters.Add(new CodePrimitiveExpression(base.Name));
         expression.Parameters.Add(new CodePrimitiveExpression(this.Value));
         return new CodeExpressionStatement(expression);
     }
     CodeExpression right = null;
     if (base.PropertyInfo != null)
     {
         expression2 = CodeDomUtility.BuildPropertyReferenceExpression(ctrlRefExpr, base.Name);
     }
     else
     {
         expression2 = new CodeFieldReferenceExpression(ctrlRefExpr, base.Name);
     }
     if (base.Type == typeof(string))
     {
         right = generator.BuildStringPropertyExpression(this);
     }
     else
     {
         right = CodeDomUtility.GenerateExpressionForValue(base.PropertyInfo, this.Value, base.Type);
     }
     return new CodeAssignStatement(expression2, right);
 }
Exemplo n.º 21
0
		public void Constructor0 ()
		{
			CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression ();
			Assert.IsNotNull (cmie.Method, "#1");
			Assert.AreEqual (string.Empty, cmie.Method.MethodName, "#2");
			Assert.IsNull (cmie.Method.TargetObject, "#3");
#if NET_2_0
			Assert.AreEqual (0, cmie.Method.TypeArguments.Count, "#4");
#endif
			Assert.IsNotNull (cmie.Parameters, "#5");
			Assert.AreEqual (0, cmie.Parameters.Count, "#6");

			CodeMethodReferenceExpression method = new CodeMethodReferenceExpression ();
			cmie.Method = method;
			Assert.IsNotNull (cmie.Method, "#7");
			Assert.AreSame (method, cmie.Method, "#8");

			cmie.Method = null;
			Assert.IsNotNull (cmie.Method, "#9");
			Assert.AreEqual (string.Empty, cmie.Method.MethodName, "#10");
			Assert.IsNull (cmie.Method.TargetObject, "#11");
#if NET_2_0
			Assert.AreEqual (0, cmie.Method.TypeArguments.Count, "#12");
#endif
		}
        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;
            }
        }
Exemplo n.º 23
0
 private CodeMethodInvokeExpression LocalMethodInvoke(string name)
 {
     var invoke = new CodeMethodInvokeExpression();
     invoke.Method.MethodName = name;
     invoke.Method.TargetObject = null;
     return invoke;
 }
Exemplo n.º 24
0
        public void Visit(WhileStatement whileStatement)
        {
            using (Scope.Push(_mainType))
            {
                var tableArg = VisitChild(whileStatement.TableReference);

                CodeMemberMethod method = new CodeMemberMethod();
                method.Name = "While_" + tableArg.MethodIdentifier;
                method.Attributes = MemberAttributes.Private;
                GenerateCallStatement(method.Statements, whileStatement.Line.Line);

                var loop = new CodeIterationStatement();
                loop.InitStatement = new CodeSnippetStatement();
                loop.IncrementStatement = new CodeSnippetStatement();
                loop.TestExpression = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(tableArg.CodeExpression, "RowCount"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(0));

                method.Statements.Add(loop);

                var blockArgs = VisitChild(whileStatement.Block, new CodeDomArg() { Tag = true });
                loop.Statements.AddRange(blockArgs.ParentStatements);

                var methodcall = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null, method.Name));

                _mainType.Type.Members.Add(method);
                _codeStack.Peek().ParentStatements.Add(methodcall);
                _codeStack.Peek().CodeExpression = methodcall;
            }
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace myNamespace = new CodeNamespace("MyNamespace");
            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass");
            CodeEntryPointMethod start = new CodeEntryPointMethod();
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World"));
            compileUnit.Namespaces.Add(myNamespace);
            myNamespace.Types.Add(myClass);
            myClass.Members.Add(start);
            start.Statements.Add(cs1);

            CSharpCodeProvider provider = new CSharpCodeProvider();

            using(StreamWriter sw = new StreamWriter("HelloWorld.cs", false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, " ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
                tw.Close();
            }

            Console.WriteLine("HelloWorld.cs generated in .../bin/Debug or .../bin/Release project folders.");

            Console.Write("Press a key to exit");
            Console.ReadKey();
        }
Exemplo n.º 26
0
        public CodeNamespace CreateCodeHelloDemo()
        {
            var method = new CodeMemberMethod();
            method.Name = "SayHello";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            method.ReturnType = new CodeTypeReference(typeof(string));
            method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello From Code!")));

            CodeEntryPointMethod main = new CodeEntryPointMethod();
            main.Statements.Add(new CodeVariableDeclarationStatement("HelloWord", "hw", new CodeObjectCreateExpression("HelloWord", new CodeExpression[] { })));

            CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("hw"), "SayHello",  new CodeExpression[] { });
            main.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"),"WriteLine",methodInvoke));
            main.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "Read"));

            CodeTypeDeclaration helloword=new CodeTypeDeclaration("HelloWord");
            helloword.Attributes=MemberAttributes.Public;
            helloword.Members.AddRange(new CodeTypeMember[]{method,main});

            CodeNamespace nspace=new CodeNamespace("HelloDemo1");
            nspace.Imports.Add(new CodeNamespaceImport("System"));

            nspace.Types.Add(helloword);
            return nspace;
        }
        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;
        }
        /// <summary>
        /// Generates the <c>IRequestProvider.CreateRequest()</c> method.
        /// </summary>
        /// <returns><c>CodeMemberMethod</c> describing the method.</returns>
        internal CodeMemberMethod GenerateCreateRequestMethod()
        {
            var method = new CodeMemberMethod();

            method.Name = CreateRequestMethodName;
            method.ImplementationTypes.Add(typeof(IRequestProvider));
            method.ReturnType = new CodeTypeReference(typeof(IRequest));
            method.Attributes = MemberAttributes.Public;
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "resource"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "method"));

            //Google.Apis.Requests.Request request = this.genericService.CreateRequest(resource, method);
            method.Statements.Add(CreateRequestLocalVar());

            // if (string.IsNullOrEmpty(APIKey) == false)
            //     request = request.WithAPIKey(APIKey)
            method.Statements.Add(CreateWithApiKey());

            // return request.WithAuthentication(authenticator);
            var statement =
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeVariableReferenceExpression("request"), "WithAuthentication"),
                    new CodeVariableReferenceExpression(ServiceClassGenerator.AuthenticatorName));
            var returnStatment = new CodeMethodReturnStatement(statement);

            method.Statements.Add(returnStatment);
            return method;
        }
Exemplo n.º 29
0
        private static string AppendCreateDictionaryLocalVariable(string dictionary, CodeDomClassBuilder builder)
        {
            var parser = new AttributeParser(dictionary);
            parser.Parse();


            var keyValuePairType = new CodeTypeReference(typeof(KeyValuePair<string,object>));

            var createDictionaryMethod = new CodeMethodInvokeExpression();


            foreach (var attribute in parser.Attributes)
            {

                var newKeyValueExpression = new CodeObjectCreateExpression {CreateType = keyValuePairType};

                var keyExpression = new CodePrimitiveExpression {Value = attribute.Name};
                newKeyValueExpression.Parameters.Add(keyExpression);

                if (attribute.Type == ParsedAttributeType.String)
                {
                    AppendStringDictValue(attribute, newKeyValueExpression);
                }
                else
                {
                    newKeyValueExpression.Parameters.Add(new CodeSnippetExpression
                                                             {
                                                                 Value = attribute.Value

                                                             });
                }

                createDictionaryMethod.Parameters.Add(newKeyValueExpression);
            }



            var getDictionaryMethod = new CodeMethodReferenceExpression
                                          {
                                              MethodName = "GetDictionaryFromKeyValue",
                                              TargetObject =
                                                  new CodeVariableReferenceExpression
                                                      {
                                                          VariableName = "NHamlMonoRailView"
                                                      }
                                          };
            createDictionaryMethod.Method = getDictionaryMethod;

            var variableName = string.Format("nhamlTempDictionary{0}", tempDictionaryCount);
            tempDictionaryCount++;
            var dictionaryDecleration = new CodeVariableDeclarationStatement
                             {
                                 InitExpression = createDictionaryMethod,
                                 Name = variableName,
                                 Type = new CodeTypeReference(typeof (IDictionary<string, object>))
                             };
            builder.RenderMethod.Statements.Add(dictionaryDecleration);
            return variableName;
        }
Exemplo n.º 30
0
 public void DecorateMethodAfterExecute(IResource resource, IMethod method, CodeMemberMethod codeMember)
 {
     var logCall = new CodeMethodInvokeExpression();
     logCall.Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(LoggerName), "Debug");
     logCall.Parameters.Add(
         new CodePrimitiveExpression(String.Format("Done Executing {0}.{1}", resource.Name, method.Name)));
     codeMember.Statements.Add(logCall);
 }
 private void Initialize()
 {
     _methodInvokeExpr = new CodeMethodInvokeExpression(
         new CodeTypeReferenceExpression(
             typeof (Array)),
         "CreateInstance");
     base.Expression = _methodInvokeExpr;
 }
Exemplo n.º 32
0
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression ();
			Assert.IsNull (cmie.Method.TargetObject, "Method.TargetObject");
			Assert.AreEqual (String.Empty, cmie.Method.MethodName, "Method.MethodName");
			cmie.Method = new CodeMethodReferenceExpression ();
			Assert.AreEqual (0, cmie.Parameters.Count, "Parameters");
		}
        public void Visit(TakeAttributeStatement statement)
        {
            var expression = new CodeMethodInvokeExpression();
            expression.Method.MethodName = "TakeAttribute";
            expression.Parameters.Add(new CodePrimitiveExpression(statement.Attriute));

            _codeStack.Peek().CodeExpression = expression;
        }
        /// <summary>
        /// Generates code
        /// </summary>
        /// <param name="source">The dependence object</param>
        /// <param name="classType">Type of the class.</param>
        /// <param name="method">The initialize method.</param>
        /// <param name="generateField"></param>
        /// <returns></returns>
        public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField)
        {
            CodeExpression fieldReference = base.Generate(source, classType, method, generateField);

            ItemsControl itemsControl = source as ItemsControl;
            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, ItemsControl.ItemsPanelProperty);
            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, ItemsControl.ItemTemplateProperty);

            if (itemsControl.Items.Count > 0)
            {
                TypeGenerator typeGenerator = new TypeGenerator();
                ValueGenerator valueGenerator = new ValueGenerator();

                CodeMemberMethod itemsMethod = new CodeMemberMethod();
                itemsMethod.Attributes = MemberAttributes.Static | MemberAttributes.Private;
                itemsMethod.Name = "Get_" + itemsControl.Name + "_Items";
                itemsMethod.ReturnType = new CodeTypeReference(typeof(ObservableCollection<object>));
                classType.Members.Add(itemsMethod);

                CodeVariableDeclarationStatement collection = new CodeVariableDeclarationStatement(
                    typeof(ObservableCollection<object>), "items", new CodeObjectCreateExpression(typeof(ObservableCollection<object>)));
                itemsMethod.Statements.Add(collection);

                CodeVariableReferenceExpression itemsVar = new CodeVariableReferenceExpression("items");
                foreach (var item in itemsControl.Items)
                {
                    Type itemType = item.GetType();
                    CodeExpression itemExpr = null;
                    if (typeGenerator.HasGenerator(itemType))
                    {
                        itemExpr = typeGenerator.ProcessGenerators(item, classType, itemsMethod, false);
                    }
                    else
                    {
                        itemExpr = valueGenerator.ProcessGenerators(classType, itemsMethod, item, itemsControl.Name);
                    }

                    if (itemExpr != null)
                    {
                        CodeMethodInvokeExpression addItem = new CodeMethodInvokeExpression(itemsVar, "Add", itemExpr);
                        itemsMethod.Statements.Add(addItem);
                    }
                    else
                    {
                        CodeComHelper.GenerateError(itemsMethod, string.Format("Type {0} in Items Control collection not supported", itemType.Name));
                    }
                }

                CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(itemsVar);
                itemsMethod.Statements.Add(returnStatement);

                method.Statements.Add(new CodeAssignStatement(
                    new CodeFieldReferenceExpression(fieldReference, "ItemsSource"),
                    new CodeMethodInvokeExpression(null, itemsMethod.Name)));
            }

            return fieldReference;
        }
 public static CodeMethodInvokeExpression Clone(this CodeMethodInvokeExpression expression)
 {
     if (expression == null) return null;
     CodeMethodInvokeExpression e = new CodeMethodInvokeExpression();
     e.Method = expression.Method.Clone();
     e.Parameters.AddRange(expression.Parameters.Clone());
     e.UserData.AddRange(expression.UserData);
     return e;
 }
Exemplo n.º 36
0
        protected override void GenerateMethodInvokeExpression(System.CodeDom.CodeMethodInvokeExpression methodInvoke)
        {
            CodeMethodReferenceExpression methodRef = methodInvoke.Method;

            if (methodRef.TargetObject != null)
            {
                GenerateExpression(methodRef.TargetObject);
                Output.Write(".");
            }
            Output.Write(methodRef.MethodName);
            OutputParameters(methodInvoke.Parameters);
            //Output.Write(";");
        }
Exemplo n.º 37
0
    public static System.CodeDom.CodeCompileUnit BuildGraph()
    {
        System.CodeDom.CodeCompileUnit CompileUnit = new System.CodeDom.CodeCompileUnit();

        System.CodeDom.CodeNamespace nSpace = new System.CodeDom.CodeNamespace("HelloWorldViaCodeDOM");
        CompileUnit.Namespaces.Add(nSpace);

        nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System"));

        System.CodeDom.CodeTypeDeclaration clsStartup = new System.CodeDom.CodeTypeDeclaration("Startup");
        nSpace.Types.Add(clsStartup);

        System.CodeDom.CodeEntryPointMethod        main   = new System.CodeDom.CodeEntryPointMethod();
        System.CodeDom.CodePrimitiveExpression     exp    = new System.CodeDom.CodePrimitiveExpression("Hello World!");
        System.CodeDom.CodeTypeReferenceExpression refExp = new System.CodeDom.CodeTypeReferenceExpression("System.Console");
        System.CodeDom.CodeMethodInvokeExpression  invoke = new System.CodeDom.CodeMethodInvokeExpression(refExp, "WriteLine", exp);
        main.Statements.Add(new System.CodeDom.CodeExpressionStatement(invoke));

        clsStartup.Members.Add(main);

        return(CompileUnit);
    }
        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;
            }
        }