protected void ResourceCallAddBodyDeclaration(IMethod method,
                                                      CodeMemberMethod member,
                                                      CodeTypeReference bodyType,
                                                      bool addBodyIfUnused)
        {
            switch (method.HttpMethod)
            {
                case Request.GET:
                case Request.DELETE:
                    if (!addBodyIfUnused)
                    {
                        break;
                    }

                    // string body = null;
                    var bodyVarDeclaration = new CodeVariableDeclarationStatement(bodyType, "body");
                    bodyVarDeclaration.InitExpression = new CodePrimitiveExpression(null);
                    member.Statements.Add(bodyVarDeclaration);
                    break;

                case Request.PUT:
                case Request.POST:
                case Request.PATCH:
                    // add body Parameter.
                    member.Parameters.Add(new CodeParameterDeclarationExpression(bodyType, "body"));
                    break;
                default:
                    throw new NotSupportedException("Unsupported HttpMethod [" + method.HttpMethod + "]");
            }
        }
		public virtual object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			if (manager == null)
				throw new ArgumentNullException ("manager");

			bool isComplete = true;
			CodeStatementCollection statements = new CodeStatementCollection ();
			ExpressionContext context = manager.Context[typeof (ExpressionContext)] as ExpressionContext;
			object serialized = null;

			if (context != null && context.PresetValue == value) {
				string varName = base.GetUniqueName (manager, value);
				CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement (value.GetType (), varName); // declare
				statement.InitExpression = base.SerializeCreationExpression (manager, value, out isComplete); // initialize
				base.SetExpression (manager, value, statement.InitExpression);
				statements.Add (statement);
				serialized = statement;
			} else {
				string name = manager.GetName (value);
				if (name == null)
					name = base.GetUniqueName (manager, value);
				serialized = GetFieldReference (manager, name);
			}

			base.SerializeProperties (manager, statements, value, new Attribute[0]);
			base.SerializeEvents (manager, statements, value, new Attribute[0]);

			return serialized;
		}
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression;
     CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
     RootContext context = manager.Context[typeof(RootContext)] as RootContext;
     CodeStatementCollection statements = new CodeStatementCollection();
     if ((declaration != null) && (context != null))
     {
         CodeMemberField field = new CodeMemberField(typeof(IContainer), "components") {
             Attributes = MemberAttributes.Private
         };
         declaration.Members.Add(field);
         expression = new CodeFieldReferenceExpression(context.Expression, "components");
     }
     else
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(IContainer), "components");
         statements.Add(statement);
         expression = new CodeVariableReferenceExpression("components");
     }
     base.SetExpression(manager, value, expression);
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(typeof(Container), new CodeExpression[0]);
     CodeAssignStatement statement2 = new CodeAssignStatement(expression, right);
     statement2.UserData["IContainer"] = "IContainer";
     statements.Add(statement2);
     return statements;
 }
示例#4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CodeLocalVariableBinder"/> class
 /// with a local variable declaration.
 /// </summary>
 /// <param name="method">The method to add a <see cref="CodeTypeReference"/> to.</param>
 /// <param name="variableDeclaration">The variable declaration to add.</param>
 internal CodeLocalVariableBinder(CodeMemberMethod method, CodeVariableDeclarationStatement variableDeclaration)
 {
     Guard.NotNull(() => method, method);
     Guard.NotNull(() => variableDeclaration, variableDeclaration);
     this.method = method;
     this.variableDeclaration = variableDeclaration;
 }
        private static CodeExpression GetControlTemplateValueExpression(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName)
        {
            ControlTemplate controlTemplate = value as ControlTemplate;
            DependencyObject content = controlTemplate.LoadContent();
            string variableName = baseName + "_ct";
            string creator = CodeComHelper.GenerateTemplate(parentClass, method, content, variableName);
            Type targetType = controlTemplate.TargetType;
            CodeVariableDeclarationStatement controlTemplateVar;
            if (targetType != null)
            {
                controlTemplateVar = new CodeVariableDeclarationStatement(
                    "ControlTemplate", variableName,
                    new CodeObjectCreateExpression("ControlTemplate", new CodeTypeOfExpression(targetType.Name), new CodeSnippetExpression(creator)));
            }
            else
            {
                controlTemplateVar = new CodeVariableDeclarationStatement(
                    "ControlTemplate", variableName,
                    new CodeObjectCreateExpression("ControlTemplate", new CodeSnippetExpression(creator)));
            }

            method.Statements.Add(controlTemplateVar);

            TriggerCollection triggers = controlTemplate.Triggers;
            CodeComHelper.GenerateTriggers(parentClass, method, variableName, targetType, triggers);

            return new CodeVariableReferenceExpression(variableName);
        }
        internal static void BuildExpressionSetup(ControlBuilder controlBuilder, CodeStatementCollection methodStatements, CodeStatementCollection statements, CodeLinePragma linePragma, bool isTwoWayBound, bool designerMode) {
            // {{controlType}} target;
            CodeVariableDeclarationStatement targetDecl = new CodeVariableDeclarationStatement(controlBuilder.ControlType, "dataBindingExpressionBuilderTarget");
            methodStatements.Add(targetDecl);

            CodeVariableReferenceExpression targetExp = new CodeVariableReferenceExpression(targetDecl.Name);

            // target = ({{controlType}}) sender;
            CodeAssignStatement setTarget = new CodeAssignStatement(targetExp,
                                                                    new CodeCastExpression(controlBuilder.ControlType,
                                                                                           new CodeArgumentReferenceExpression("sender")));
            setTarget.LinePragma = linePragma;
            statements.Add(setTarget);

            Type bindingContainerType = controlBuilder.BindingContainerType;
            CodeVariableDeclarationStatement containerDecl = new CodeVariableDeclarationStatement(bindingContainerType, "Container");
            methodStatements.Add(containerDecl);

            // {{containerType}} Container = ({{containerType}}) target.BindingContainer;
            CodeAssignStatement setContainer = new CodeAssignStatement(new CodeVariableReferenceExpression(containerDecl.Name),
                                                                       new CodeCastExpression(bindingContainerType,
                                                                                              new CodePropertyReferenceExpression(targetExp,
                                                                                                                                  "BindingContainer")));
            setContainer.LinePragma = linePragma;
            statements.Add(setContainer);
            string variableName = isTwoWayBound ? "BindItem" : "Item";
            GenerateItemTypeExpressions(controlBuilder, methodStatements, statements, linePragma, variableName);
            //Generate code for other variable as well at design time in addition to runtime variable for intellisense to work.
            if (designerMode) {
                GenerateItemTypeExpressions(controlBuilder, methodStatements, statements, linePragma, isTwoWayBound ?  "Item" : "BindItem");
            }
        }
        internal BindingElementExtensionSectionGenerator(Type bindingElementType, Assembly userAssembly, CodeDomProvider provider)
        {
            this.bindingElementType = bindingElementType;
            this.userAssembly = userAssembly;
            this.provider = provider;

            string typePrefix = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement));
            this.generatedClassName = typePrefix + Constants.ElementSuffix;
            this.constantsClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.ConfigurationStrings;
            this.defaultValuesClassName = bindingElementType.Name.Substring(0, bindingElementType.Name.IndexOf(TypeNameConstants.BindingElement)) + Constants.Defaults;

            this.customBEVarInstance = Helpers.TurnFirstCharLower(bindingElementType.Name);
            customBEArgRef = new CodeArgumentReferenceExpression(customBEVarInstance);

            this.customBETypeRef = new CodeTypeReference(bindingElementType.Name);
            this.customBETypeOfRef = new CodeTypeOfExpression(customBETypeRef);
            this.customBENewVarAssignRef = new CodeVariableDeclarationStatement(
                                                customBETypeRef,
                                                customBEVarInstance,
                                                new CodeObjectCreateExpression(customBETypeRef));
            this.bindingElementMethodParamRef = new CodeParameterDeclarationExpression(
                                                    CodeDomHelperObjects.bindingElementTypeRef,
                                                    Constants.bindingElementParamName);

        }
示例#8
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);
        }
 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]));
 }
示例#10
0
 protected string CreateObject(Type type, string proposedName)
 {
     var variableName = State.GetVariableName(proposedName);
     var variableDeclaration = new CodeVariableDeclarationStatement(
         type.Name, variableName, new CodeObjectCreateExpression(type.Name));
     State.AddStatement(variableDeclaration);
     return variableName;
 }
        public virtual IEnumerable<CodeStatement> GetInitializationStatements(AggregateFunctionContext context)
        {
            CodeExpression[] parameters = new CodeExpression[0];
            CodeStatement st = new CodeVariableDeclarationStatement(context.ImplementationType, context.FunctionObjectName,
                            new CodeObjectCreateExpression(context.ImplementationType, parameters));

            return new CodeStatement[] {st};
        }
		public virtual CodeExpression GenerateInstanceExpression (ObjectWrapper wrapper, CodeExpression newObject)
		{
			string varName = NewId ();
			CodeVariableDeclarationStatement varDec = new CodeVariableDeclarationStatement (wrapper.WrappedTypeName.ToGlobalTypeRef (), varName);
			varDec.InitExpression = newObject;
			statements.Add (varDec);
			return new CodeVariableReferenceExpression (varName);
		}
        public static Tuple<CodeVariableDeclarationStatement, CodeVariableReferenceExpression> CreateVariable(CodeTypeReference typeReference, string name, params CodeExpression[] constructorParameters)
        {
            CodeObjectCreateExpression initializer = new CodeObjectCreateExpression(typeReference, constructorParameters);
            CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeReference, name, initializer);
            CodeVariableReferenceExpression reference = new CodeVariableReferenceExpression(name);

            return new Tuple<CodeVariableDeclarationStatement, CodeVariableReferenceExpression>(statement, reference);
        }
        /// <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;
        }
 private static CodeExpression GetSoundSourceCollectionValueExpression(CodeMemberMethod method, object value, string baseName)
 {
     string collVar = baseName + "_sounds";
     CodeVariableDeclarationStatement collection =
             new CodeVariableDeclarationStatement("var", collVar, new CodeObjectCreateExpression("SoundSourceCollection"));
     method.Statements.Add(collection);
     CodeComHelper.GenerateSoundSources(method, value as SoundSourceCollection, collVar);
     return new CodeVariableReferenceExpression(collVar);
 }         
示例#16
0
		public override void Compile(IEnumerable<IColumInfoModel> columnInfos, Stream to = null)
		{
			if (string.IsNullOrEmpty(TableName))
			{
				TableName = TargetCsName;
			}

			var spAttribute = new CodeAttributeDeclaration(typeof(StoredProcedureAttribute).Name);
			_base.CustomAttributes.Add(spAttribute);

			if (_base.TypeParameters.Count == 0)
			{
				//_base.TypeParameters.Add(new CodeTypeParameter(typeof ().FullName));
			}

			//Create Caller
			var createFactoryMethod = new CodeMemberMethod();
			createFactoryMethod.Name = "Invoke" + TableName;
			createFactoryMethod.ReturnType = new CodeTypeReference(typeof(QueryFactoryResult));
			createFactoryMethod.CustomAttributes.Add(
				new CodeAttributeDeclaration(typeof(SelectFactoryMethodAttribute).FullName));

			//Create the Params
			string query = "EXEC " + TableName;

			var nameOfListOfParamater = "paramaters";
			var listOfParams = new CodeObjectCreateExpression(typeof(List<IQueryParameter>));
			var listOfParamscreator = new CodeVariableDeclarationStatement(typeof(List<IQueryParameter>), nameOfListOfParamater, listOfParams);
			createFactoryMethod.Statements.Add(listOfParamscreator);
			int i = 0;
			foreach (var item in _base.Members)
			{
				if (item is CodeMemberProperty)
				{
					var variable = item as CodeMemberProperty;
					var paramName = "param" + i++;
					query += " @" + paramName + " ";
					var createParams = new CodeObjectCreateExpression(typeof(QueryParameter),
						new CodePrimitiveExpression(paramName),
						new CodeVariableReferenceExpression(variable.Name));
					var addToList =
						new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(nameOfListOfParamater),
							"Add", createParams);

					createFactoryMethod.Statements.Add(addToList);
				}
			}

			//Finaly create the instance
			var createFactory = new CodeObjectCreateExpression(typeof(QueryFactoryResult),
				new CodePrimitiveExpression(query),
				new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(nameOfListOfParamater), "ToArray"));
			var queryFactoryVariable = new CodeMethodReturnStatement(createFactory);

			createFactoryMethod.Statements.Add(queryFactoryVariable);
			_base.Members.Add(createFactoryMethod);
		}
        private static string AddObjectInstance(CodeMemberMethod method, object instance, InstanceManager instanceManager)
        {
            Type type = instance.GetType();
            if (instanceManager.ConstainsInstance(instance))
                return instanceManager.GetInstanceName(instance);

            string variableName = instanceManager.GetInstanceName(instance);
            CodeVariableDeclarationStatement objectVariable = new CodeVariableDeclarationStatement(
                type.Name, variableName, new CodeObjectCreateExpression(type.Name,
                new CodeVariableReferenceExpression("session")));

            method.Statements.Add(objectVariable);
            var ti = XafTypesInfo.Instance.FindTypeInfo(type);
            foreach (var member in ti.Members.Where(m => ((m.MemberType.IsPrimitive || m.MemberType == typeof(string))
                && m.IsPersistent && m.IsPublic)))
            {
                object value = member.GetValue(instance);
                if (value != null)
                {
                    method.Statements.Add(new CodeAssignStatement(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(variableName), member.Name),
                        new CodePrimitiveExpression(value)));
                }
            }

            foreach (var member in ti.Members.Where(m => m.MemberTypeInfo.IsPersistent && m.IsPublic && !m.IsReferenceToOwner))
            {
                object value = member.GetValue(instance);

                if (value != null)
                {
                    string valueName = AddObjectInstance(method, value, instanceManager);
                    method.Statements.Add(new CodeAssignStatement(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(variableName), member.Name),
                        new CodeVariableReferenceExpression(valueName)));
                }
            }

            foreach (var member in ti.Members.Where(m => m.IsAssociation && m.IsList && m.IsPublic))
            {
                IList list = member.GetValue(instance) as IList;

                if (list != null && list.Count > 0)
                {
                    foreach (object value in list)
                    {
                        string valueName = AddObjectInstance(method, value, instanceManager);
                        method.Statements.Add(new CodeMethodInvokeExpression(
                            new CodeMethodReferenceExpression(
                                new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(variableName), member.Name), "Add"),
                                new CodeVariableReferenceExpression(valueName)));
                    }
                }
            }

            return variableName;
        }
示例#18
0
        public async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(System.CodeDom.CodeMemberMethod Method, string valueName)
        {
            await EngineNS.Thread.AsyncDummyClass.DummyFunc();

            var param = CSParam as CreateObjectConstructionParams;

            // 生成创建的代码
            if (mVarDec == null || !Method.Statements.Contains(mVarDec))
            {
                //var valueName = GCode_GetValueName(null, context);
                if (mTemplateClassInstance != null)
                {
                    var type = mTemplateClassInstance.GetType();
                    foreach (var pro in mClassProperties)
                    {
                        var proInfo = type.GetProperty(pro.PropertyName);
                        if (proInfo == null)
                        {
                            continue;
                        }

                        var defProInfo = param.CreateType.GetProperty(pro.PropertyName);
                        var curValue   = proInfo.GetValue(mTemplateClassInstance);
                        var defValue   = defProInfo.GetValue(mDefaultValueObj);
                        if (object.Equals(curValue, defValue))
                        {
                            continue;
                        }
                        if (pro.PropertyType.FullName == typeof(EngineNS.RName).FullName)
                        {
                            var rname = curValue as EngineNS.RName;
                            if (rname == null)
                            {
                                Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodePrimitiveExpression(null)));
                            }
                            else
                            {
                                Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName),
                                                                                    new CodeSnippetExpression($"EngineNS.CEngine.Instance.FileManager.GetRName(\"{rname.Name}\", {EngineNS.Rtti.RttiHelper.GetAppTypeString(typeof(EngineNS.RName.enRNameType))}.{rname.RNameType.ToString()})")));
                            }
                        }
                        else if (pro.PropertyType.IsEnum)
                        {
                            Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodeVariableReferenceExpression(EngineNS.Rtti.RttiHelper.GetAppTypeString(pro.PropertyType) + "." + curValue.ToString())));
                        }
                        else
                        {
                            Method.Statements.Insert(0, new CodeAssignStatement(new CodeVariableReferenceExpression(valueName + "." + pro.PropertyName), new CodePrimitiveExpression(curValue)));
                        }
                    }
                }

                mVarDec = new System.CodeDom.CodeVariableDeclarationStatement(param.CreateType, valueName, new CodeObjectCreateExpression(param.CreateType, new CodeExpression[0]));
                Method.Statements.Insert(0, mVarDec);
            }
        }
示例#19
0
	static ResultBuilder ()
	{
	    // @{int base_total = base.NumFielduments;}

	    BaseTotalItems = new CodeVariableDeclarationStatement ();
	    BaseTotalItems.Name = "base_total";
	    BaseTotalItems.Type = new CodeTypeReference (typeof (int));
	    BaseTotalItems.InitExpression = 
		new CodePropertyReferenceExpression (CDH.Base, "TotalItems");
	}
		public void Constructor2_Deny_Unrestricted ()
		{
			CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement ("System.Int32", "mono");
			Assert.IsNull (cvds.InitExpression, "InitExpression");
			cvds.InitExpression = new CodeExpression ();
			Assert.AreEqual ("mono", cvds.Name, "Name");
			cvds.Name = String.Empty;
			Assert.AreEqual ("System.Int32", cvds.Type.BaseType, "Type");
			cvds.Type = new CodeTypeReference ("System.Void");
		}
示例#21
0
	static RuleBuilder ()
	{
	    // @{int base_total = base.NumArguments;}

	    BaseNumArgs = new CodeVariableDeclarationStatement ();
	    BaseNumArgs.Name = "base_total";
	    BaseNumArgs.Type = new CodeTypeReference (typeof (int));
	    BaseNumArgs.InitExpression = 
		new CodePropertyReferenceExpression (CDH.Base, "NumArguments");
	}
示例#22
0
        void EmitVariableDeclarationStatement(CodeVariableDeclarationStatement Statement)
        {
            if(Locals.ContainsKey(Statement.Name))
                throw new CompileException(Statement, "Attempt to redefine local variable "+Statement.Name);

            Type Top = EmitExpression(Statement.InitExpression);
            LocalBuilder Local = Generator.DeclareLocal(Top);
            Locals.Add(Statement.Name, Local);

            Generator.Emit(OpCodes.Stloc, Local);
        }
 public TypescriptVariableDeclarationStatement(
     IStatementFactory statementFactory,
     IExpressionFactory expressionFactory,
     CodeVariableDeclarationStatement statement,
     CodeGeneratorOptions options)
 {
     _statementFactory = statementFactory;
     _expressionFactory = expressionFactory;
     _statement = statement;
     _options = options;
     _typescriptTypeMapper = new TypescriptTypeMapper();
 }
示例#24
0
        public override IEnumerable<CodeStatement> GetInitializationStatements(AggregateFunctionContext context)
        {
            List<CodeStatement> statements = new List<CodeStatement>(base.GetInitializationStatements(context));

            CodeStatement st = new CodeVariableDeclarationStatement(typeof(int),
                GetCounterObjectName(context),
                new CodeSnippetExpression("0"));

            statements.Add(st);

            return statements;
        }
示例#25
0
 protected override void GenerateVariableDeclarationStatement(System.CodeDom.CodeVariableDeclarationStatement e)
 {
     Output.Write("var " + e.Name + ": ");
     OutputType(e.Type);
     if (e.InitExpression != null)
     {
         Output.Write(" := ");
         GenerateExpression(e.InitExpression);
     }
     Output.WriteLine(";");
     //throw new Exception("The method or operation is not implemented.");
 }
示例#26
0
        internal FORMALS formals;    // optional


        public CodeMemberMethod ToCodeMemberMethod()
        {
            CodeMemberMethod method;

            if (method_id == "initialize")
                method = new CodeConstructor();
            else
                method = new CodeMemberMethod();

            method.Name = method_id;
            method.ReturnType = new CodeTypeReference(typeof(object));

            method.Parameters.AddRange(formals.ToCodeParameterDeclarationExpressionCollection());

            if (method_id == "InitializeComponent")
                for (Node n = body; n != null; n = n.nd_next)
                {

                    if (n is ASSIGNMENT)
                    {
                        CodeStatement stmt = null;
                        Node lhs = ((ASSIGNMENT)n).lhs;
                        Node rhs = ((ASSIGNMENT)n).rhs;
                        if (rhs is METHOD_CALL)
                        {
                            METHOD_CALL m = (METHOD_CALL)rhs;
                            if (m.receiver.ToString() == "Interop" && m.method_id == "VariableDeclaration")
                            {
                                Node init = ((ARGS)m.args).parameters;
                                Node type = init.nd_next;
                                stmt = new CodeVariableDeclarationStatement(type.ToString().Replace("::","."), lhs.ToString(), init.ToCodeExpression());
                            }
                        }

                        if (stmt == null)
                            stmt = ((ASSIGNMENT)n).ToCodeStatement();
                        
                        method.Statements.Add(stmt);
                    }
                    else if (n is METHOD_CALL)
                        method.Statements.Add(n.ToCodeExpression());
                    else
                        throw new System.NotImplementedException(n.GetType().ToString());
                }
            else if (body != null)
                method.Statements.Add(new CodeCommentStatement("Dummy statement so that it doesn't appear empty to the designer"));

            method.UserData["original_name"] = method.Name;
            method.UserData["name_location"] = name_location;
            method.UserData["location"] = this.location;

            return method;
        }
 private static CodeExpression GetItemsPanelTemplateValueExpression(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName)
 {
     ItemsPanelTemplate template = value as ItemsPanelTemplate;
     DependencyObject content = template.LoadContent();
     string variableName = baseName + "_ipt";
     string creator = CodeComHelper.GenerateTemplate(parentClass, method, content, variableName);
     CodeVariableDeclarationStatement templateVar = new CodeVariableDeclarationStatement(
             "ControlTemplate", variableName,
             new CodeObjectCreateExpression("ControlTemplate", new CodeSnippetExpression(creator)));
     method.Statements.Add(templateVar);
     return new CodeVariableReferenceExpression(variableName);
 }
示例#28
0
 private void GenerateConstructorWithTextParameter(CodeTypeDeclaration classObject, JsonObject jsonObject)
 {
     CodeConstructor constructor = new CodeConstructor();
     classObject.Members.Add(constructor);
     constructor.Attributes = MemberAttributes.Public;
     constructor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "text"));
     CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(JsonTextParser), "parser", new CodeObjectCreateExpression(new CodeTypeReference(typeof(JsonTextParser)), new CodeExpression[0]));
     constructor.Statements.Add(statement);
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("parser"), "Parse"), new CodeExpression[] { new CodeVariableReferenceExpression("text") });
     CodeAssignStatement statement2 = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "RootObject"), new CodeCastExpression(new CodeTypeReference(jsonObject.GetType()), expression));
     constructor.Statements.Add(statement2);
     constructor.Statements.Add(new CodeMethodReturnStatement());
 }
 public static CodeVariableDeclarationStatement Clone(this CodeVariableDeclarationStatement statement)
 {
     if (statement == null) return null;
     CodeVariableDeclarationStatement s = new CodeVariableDeclarationStatement();
     s.EndDirectives.AddRange(statement.EndDirectives);
     s.InitExpression = statement.InitExpression.Clone();
     s.LinePragma = statement.LinePragma;
     s.Name = statement.Name;
     s.StartDirectives.AddRange(statement.StartDirectives);
     s.Type = statement.Type.Clone();
     s.UserData.AddRange(statement.UserData);
     return s;
 }
 internal static void BuildExpressionSetup(ControlBuilder controlBuilder, CodeStatementCollection methodStatements, CodeStatementCollection statements)
 {
     CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(controlBuilder.ControlType, "dataBindingExpressionBuilderTarget");
     methodStatements.Add(statement);
     CodeVariableReferenceExpression left = new CodeVariableReferenceExpression(statement.Name);
     CodeAssignStatement statement2 = new CodeAssignStatement(left, new CodeCastExpression(controlBuilder.ControlType, new CodeArgumentReferenceExpression("sender")));
     statements.Add(statement2);
     Type bindingContainerType = controlBuilder.BindingContainerType;
     CodeVariableDeclarationStatement statement3 = new CodeVariableDeclarationStatement(bindingContainerType, "Container");
     methodStatements.Add(statement3);
     CodeAssignStatement statement4 = new CodeAssignStatement(new CodeVariableReferenceExpression(statement3.Name), new CodeCastExpression(bindingContainerType, new CodePropertyReferenceExpression(left, "BindingContainer")));
     statements.Add(statement4);
 }
示例#31
0
        public override IEnumerable<CodeStatement> GetInitializationStatements(AggregateFunctionContext context)
        {
            MemberMappingDescriptor member = context.Member;
            Type resultType;
            Type instanceType;
            bool isSimpleMapping = false;
            if (member.IsArray || member.IsList)
            {
                instanceType = member.IsArray ?
                    member.AggregateMappingDescription.TargetType.GetElementType() :
                    member.AggregateMappingDescription.TargetType.GetGenericArguments()[0];
                resultType = typeof(List<>).MakeGenericType(instanceType);

                if (!instanceType.IsPrimitive && instanceType != typeof(string))
                {
                    m_expression = string.Format("{{0}}.Add({0}.AssembleFrom({{1}}));", GetAssemblerName(context));
                }
                else
                {
                    m_expression = "{0}.Add({1});";
                    isSimpleMapping = true;
                }
            }
            else
            {
                string msg = ErrorBuilder.CantAggregateOverNoncollectionError(member, "collect");
                throw new OtisException(msg); //todo: test
            }

            m_isArray = member.IsArray;
            List<CodeStatement> statements = new List<CodeStatement>();

            CodeExpression[] parameters = new CodeExpression[0];
            CodeStatement st = new CodeVariableDeclarationStatement(resultType,
                context.FunctionObjectName,
                new CodeObjectCreateExpression(resultType, parameters));

            statements.Add(st);

            if(!isSimpleMapping)
            {
                st = new CodeVariableDeclarationStatement(
                    string.Format("IAssembler<{0}, {1}>", TypeHelper.GetTypeDefinition(instanceType), TypeHelper.GetTypeDefinition(context.SourceItemType)),
                    GetAssemblerName(context),
                    new CodeSnippetExpression("this"));
                statements.Add(st);
            }

            return statements;
        }
示例#32
0
 private CodeExpression BuildClass(CodeStatementCollection statements, string name, object value)
 {
     Type type = value.GetType();
     string uniqueVariableName = GetUniqueVariableName(name, statements);
     CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(type.FullName, uniqueVariableName);
     statement.InitExpression = new CodeObjectCreateExpression(type.FullName, new CodeExpression[0]);
     statements.Add(statement);
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(uniqueVariableName);
     foreach (MemberInfo info in type.GetMembers(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance))
     {
         object obj2 = null;
         Type fieldType = typeof(object);
         CodeExpression left = null;
         if (info is FieldInfo)
         {
             FieldInfo info2 = (FieldInfo) info;
             if (info2.IsStatic || info2.IsInitOnly)
             {
                 goto Label_014B;
             }
             fieldType = info2.FieldType;
             obj2 = info2.GetValue(value);
             left = new CodeFieldReferenceExpression(targetObject, info2.Name);
         }
         else if (info is PropertyInfo)
         {
             PropertyInfo info3 = (PropertyInfo) info;
             if (!info3.CanWrite)
             {
                 goto Label_014B;
             }
             MethodInfo getMethod = info3.GetGetMethod();
             if ((getMethod.GetParameters().Length > 0) || getMethod.IsStatic)
             {
                 goto Label_014B;
             }
             fieldType = info3.PropertyType;
             obj2 = info3.GetValue(value, null);
             left = new CodePropertyReferenceExpression(targetObject, info3.Name);
         }
         if (left != null)
         {
             CodeExpression right = this.BuildObject(statements, info.Name, obj2);
             statements.Add(new CodeAssignStatement(left, right));
         }
     Label_014B:;
     }
     return targetObject;
 }
示例#33
0
        public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Method context)
        {
            if (element == null || element == mCtrlMethodIn)
            {
                var param     = CSParam as ClassCastControlConstructParam;
                var paramName = GCode_GetValueName(mCastResultPin, context);

                if (!mTargetPin.GetLinkedObject(0).IsOnlyReturnValue)
                {
                    await mTargetPin.GetLinkedObject(0).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, mTargetPin.GetLinkedPinControl(0), context);
                }

                if (!context.Method.Statements.Contains(mVariableDeclaration))
                {
                    mVariableDeclaration = new CodeVariableDeclarationStatement(param.ResultType, paramName, new CodePrimitiveExpression(null));
                    context.Method.Statements.Insert(0, mVariableDeclaration);
                }

                #region Debug
                // 收集用于调试的数据的代码
                var debugCodes = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(codeStatementCollection);
                CodeDomNode.BreakPoint.GetGatherDataValueCodeStatement(debugCodes, TargetPin.GetLinkPinKeyName(), GCode_CodeDom_GetValue(mTargetPin, context), GCode_GetTypeString(mTargetPin, context), context);
                var breakCondStatement = CodeDomNode.BreakPoint.BreakCodeStatement(codeClass, debugCodes, HostNodesContainer.GUID, Id);
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(codeStatementCollection, debugCodes);
                #endregion

                var tryCatchStatement = new CodeTryCatchFinallyStatement();
                codeStatementCollection.Add(tryCatchStatement);
                tryCatchStatement.TryStatements.Add(new CodeAssignStatement(
                                                        new CodeVariableReferenceExpression(paramName),
                                                        new CodeGenerateSystem.CodeDom.CodeCastExpression(
                                                            param.ResultType,
                                                            mTargetPin.GetLinkedObject(0).GCode_CodeDom_GetValue(mTargetPin.GetLinkedPinControl(0), context))));

                var catchClause = new CodeCatchClause("catchException", new CodeTypeReference(typeof(System.Exception)),
                                                      new CodeAssignStatement(
                                                          new CodeVariableReferenceExpression(paramName),
                                                          new CodePrimitiveExpression(null)));
                tryCatchStatement.CatchClauses.Add(catchClause);

                #region Debug
                // 转换之后收集一次数据
                var debugCodesAfter = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(codeStatementCollection);
                CodeDomNode.BreakPoint.GetGatherDataValueCodeStatement(debugCodesAfter, CastResultPin.GetLinkPinKeyName(), GCode_CodeDom_GetValue(CastResultPin, context), GCode_GetTypeString(CastResultPin, context), context);
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(codeStatementCollection, debugCodesAfter);
                #endregion

                var condStatement = new CodeConditionStatement();
                codeStatementCollection.Add(condStatement);
                condStatement.Condition = new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression(paramName),
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null));

                if (mCtrlMethodOut.HasLink)
                {
                    await mCtrlMethodOut.GetLinkedObject(0).GCode_CodeDom_GenerateCode(codeClass, condStatement.TrueStatements, mCtrlMethodOut.GetLinkedPinControl(0), context);
                }
                if (mCastFailedPin.HasLink)
                {
                    await mCastFailedPin.GetLinkedObject(0).GCode_CodeDom_GenerateCode(codeClass, condStatement.FalseStatements, mCastFailedPin.GetLinkedPinControl(0), context);
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
        }