상속: System.CodeDom.CodeExpression
 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;
 }
 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]));
 }
예제 #3
0
        public static CodeTypeMember CreateStaticMethod(string methodName, string typeT, string typeT1, string parameterName, string parameterType, bool useAutoTyping) {
            CodeMemberMethod staticMethod = new CodeMemberMethod();
            staticMethod.Name = methodName;
            staticMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            staticMethod.ReturnType = new CodeTypeReference(typeT); 
            
            staticMethod.Parameters.Add(CreateParameter(parameterName, parameterType));
            CodeExpression parameterExp = new CodeVariableReferenceExpression(parameterName);

            if (useAutoTyping) { 
                staticMethod.Statements.Add(
                    new CodeMethodReturnStatement(
                        new CodeCastExpression(
                            staticMethod.ReturnType,
                            CreateMethodCall(
                                new CodeTypeReferenceExpression(Constants.XTypedServices),
                                Constants.ToXTypedElement, 
                                CreateMethodCall(new CodeTypeReferenceExpression(Constants.XElement), methodName, parameterExp),
                                CodeDomHelper.SingletonTypeManager()))));
            }
            else {
                CodeMethodInvokeExpression methodCall = CreateMethodCall(new CodeTypeReferenceExpression(Constants.XTypedServices), methodName + "<" + GetInnerType(typeT, typeT1) + ">", parameterExp);
                if (typeT1 != null) {
                    methodCall.Parameters.Add(CodeDomHelper.SingletonTypeManager());
                }
                staticMethod.Statements.Add(new CodeMethodReturnStatement(methodCall));  
            }
            return staticMethod;
        }
예제 #4
0
        public override void GenerateMappingCode(CodeGenerationContext ctx, CodeMemberMethod method)
        {
            if (!String.IsNullOrEmpty(To))
                MappedProperty = TypeReflector.GetProperty(ctx.MappedObjectType, To);

            if (MappedProperty != null)
            {
                if (MapNotBoolProperty)
                {
                    // type value = bitReader.ReadBits(length);
                    method.Statements.Add(new CodeVariableDeclarationStatement(MappedValueType, "value",
                        new CodeMethodInvokeExpression(ctx.DataReader, "ReadBits", new CodePrimitiveExpression(Length))));
                }
                else
                {
                    method.Statements.Add(
                        new CodeVariableDeclarationStatement(MappedValueType, "value",
                            new CodeBinaryOperatorExpression(
                                new CodeMethodInvokeExpression(ctx.DataReader, "ReadBits", new CodePrimitiveExpression(Length)),
                                CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(0))));
                }

                // add operations code
                CodeVariableReferenceExpression value = new CodeVariableReferenceExpression("value");
                foreach (IOperation op in Operations)
                    method.Statements.AddRange(op.BuildOperation(ctx, this, value));

                method.Statements.AddRange(GenerateSetMappedPropertyCode(ctx.MappedObject, value));
            }
            else
            {   // just read
                method.Statements.Add(
                    new CodeMethodInvokeExpression(ctx.DataReader, "ReadBits", new CodePrimitiveExpression(Length)));
            }
        }
예제 #5
0
        public override object Serialize(IDesignerSerializationManager manager, object value) {
            var baseSerializer = (CodeDomSerializer)manager
                .GetSerializer(typeof(ResourceManagerSetter).BaseType, typeof(CodeDomSerializer));
            object codeObject = baseSerializer.Serialize(manager, value);

            var statements = codeObject as CodeStatementCollection;
            if (statements != null) {
                CodeExpression leftCodeExpression = new CodeVariableReferenceExpression("resources");
                var classTypeDeclaration = (CodeTypeDeclaration)manager.GetService(typeof(CodeTypeDeclaration));
                CodeExpression typeofExpression = new CodeTypeOfExpression(classTypeDeclaration.Name);
                CodeExpression rightCodeExpression =
                    new CodeObjectCreateExpression(typeof(XafComponentResourceManager),
                                                                  new[] { typeofExpression });
                //CodeExpression rightCodeExpression =
                //    new CodeTypeReferenceExpression(
                //        "new DevExpress.ExpressApp.Win.Templates"),
                //        "XafComponentResourceManager", new[] { typeofExpression });

                statements.Insert(0, new CodeAssignStatement(leftCodeExpression, rightCodeExpression));
            }

            return codeObject;


        }
예제 #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CodeLocalVariableBinder"/> class
 /// with a reference to a variable.
 /// </summary>
 /// <param name="method">The method to add a <see cref="CodeTypeReference"/> to.</param>
 /// <param name="reference">The reference to a local variable.</param>
 internal CodeLocalVariableBinder(CodeMemberMethod method, CodeVariableReferenceExpression reference)
 {
     Guard.NotNull(() => method, method);
     Guard.NotNull(() => reference, reference);
     this.method = method;
     this.reference = reference;
 }
 public static CodeExpression Is(CodeVariableReferenceExpression var,
     CodeTypeReferenceExpression type, CodeDomProvider provider)
 {
     return new CodeSnippetExpression(
         "((" + ExpressionToString(var, provider) + ") is " +
         ExpressionToString(type, provider) + ")");
 }
        public override object Serialize(IDesignerSerializationManager manager, object obj)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");
            if (obj == null)
                throw new ArgumentNullException("obj");

            CodeExpression retVal = null;
            CodeStatementCollection statements = manager.Context[typeof(CodeStatementCollection)] as CodeStatementCollection;
            System.Diagnostics.Debug.Assert(statements != null);
            if (statements != null)
            {
                Activity activity = (Activity)manager.Context[typeof(Activity)];
                CodeExpression objectExpression = SerializeToExpression(manager, activity);
                ICollection<String> handles = obj as ICollection<String>;
                if (handles == null)
                    throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(StringCollection).FullName), "obj");

                string variableName = GetUniqueName(manager, new StringCollection());
                statements.Add(new CodeVariableDeclarationStatement(obj.GetType(), variableName, new CodeObjectCreateExpression(obj.GetType())));

                foreach (string handle in handles)
                    statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(variableName), "Add"), new CodeExpression[] { new CodePrimitiveExpression(handle) }));

                retVal = new CodeVariableReferenceExpression(variableName);
            }
            return retVal;
        }
예제 #9
0
        private CodeExpression GetPropertyValueExpression(Type propertyType, CodeVariableReferenceExpression binaryReader)
        {
            if (propertyType == typeof(byte))
                return new CodeMethodInvokeExpression (binaryReader, "ReadByte");

            if (propertyType == typeof(short))
                return new CodeMethodInvokeExpression(binaryReader, "ReadInt16");

            if (propertyType == typeof(ushort))
                return new CodeMethodInvokeExpression(binaryReader, "ReadUInt16");

            if (propertyType == typeof(int))
                return new CodeMethodInvokeExpression(binaryReader, "ReadInt32");
            
            if (propertyType == typeof(uint))
                return new CodeMethodInvokeExpression(binaryReader, "ReadUInt32");

            if (propertyType == typeof(float))
                return new CodeMethodInvokeExpression(binaryReader, "ReadSingle");

            if (propertyType == typeof(double))
                return new CodeMethodInvokeExpression(binaryReader, "ReadDouble");

            if (propertyType.IsEnum)
            {
                Type enumBaseType = Enum.GetUnderlyingType(propertyType);
                return new CodeCastExpression(propertyType, GetPropertyValueExpression(enumBaseType, binaryReader));
            }

            throw new NotSupportedException(String.Format("'{0}' doesn't support properties of type '{1}'", 
                GetType().FullName, propertyType.FullName));
        }
예제 #10
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 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");
            }
        }
예제 #12
0
 public override CodeStatementCollection BuildOperation(CodeGenerationContext ctx, ICodeGeneratorNode element, CodeVariableReferenceExpression value)
 {
     CodeStatementCollection statemets = new CodeStatementCollection();
     statemets.Add(new CodeSnippetExpression(
         string.Format("{0} = ({2})((int){0} >> {1})", value.VariableName, Value, GetValueType(element.MappedProperty).FullName)));
     return statemets;
 }
 public CodeForEachStatement(CodeTypeReference elementType, string elementName, CodeExpression enumerableTarget, params CodeStatement[] statements)
 {
     _elementType = elementType;
     _variableRefExpr = new CodeVariableReferenceExpression(elementName);
     _enumerableTarget = enumerableTarget;
     Statements.AddRange(statements);
     Refresh();
 }
예제 #14
0
        public JsonCodeWriter(CodeVariableReferenceExpression variable, IList list)
        {
            if (variable == null)
                throw new ArgumentNullException("variable");

            _variable = variable;
            _list = list;
        }
 public TypescriptVariableReferenceExpression(
     CodeVariableReferenceExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptVariableReferenceExpression Created");
 }
예제 #16
0
        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 CodeStatement createChildContainerStatement(CodeVariableReferenceExpression picoContainer,
		                                                    CodeVariableReferenceExpression childContainer)
		{
			CodeExpression[] arguments = new CodeExpression[] {picoContainer};
			CodeExpression rightHandSide = new CodeObjectCreateExpression(Constants.DefaultPicoContainerType, arguments);

			return new CodeVariableDeclarationStatement(Constants.DefaultPicoContainerType,
			                                            childContainer.VariableName,
			                                            rightHandSide);
		}
예제 #19
0
        Type EmitVariableReference(CodeVariableReferenceExpression Expr)
        {
            if(!Locals.ContainsKey(Expr.VariableName))
                throw new CompileException(Expr, "Undefined variable: "+Expr.VariableName);

            LocalBuilder Builder = Locals[Expr.VariableName];
            Generator.Emit(OpCodes.Ldloc, Builder);

            return Builder.LocalType;
        }
		public void Build(CodeMemberMethod composeMethod,
		                  CodeVariableReferenceExpression picoContainer,
		                  CodeVariableReferenceExpression childContainer)
		{
			CodeStatement childContainerStatement = createChildContainerStatement(picoContainer, childContainer);
			CodeExpression registerChildInstanceExpression = createRegisterChildInstanceExpression(picoContainer, childContainer);

			composeMethod.Statements.Add(childContainerStatement);
			composeMethod.Statements.Add(registerChildInstanceExpression);
		}
예제 #21
0
        public JsonCodeWriter(CodeVariableReferenceExpression variable, ICollector collector)
        {
            if (variable == null)
                throw new ArgumentNullException("variable");

            if (collector == null)
                throw new ArgumentNullException("collector");

            _variable = variable;
            _collector = collector;
        }
예제 #22
0
      	public override void EmitApply (CodeMemberMethod apply, CodeArgumentReferenceExpression proj,
					CodeArgumentReferenceExpression declloc, 
					CodeArgumentReferenceExpression log, 
					CodeVariableReferenceExpression pb,
					CodeVariableReferenceExpression tb)
	{
	    apply.Statements.Add (new CodeCommentStatement ("Create provider for param " +
							    basisparam));

	    CodeMethodInvokeExpression mie = new CodeMethodInvokeExpression ();
	    mie.Method = new CodeMethodReferenceExpression (proj, "EnsureProvider");
	    mie.Parameters.Add (new CodeFieldReferenceExpression (CDH.This, basisparam));
	    mie.Parameters.Add (declloc);

	    apply.Statements.Add (new CodeAssignStatement (pb, mie));

	    // Tell the PB about our Structure arguments so it can
	    // use them to instantiate the objects we reference.
	    // FIXME: catch if the provider references a rule or template 
	    // that requires a structure we don't have.

	    //if (Structure != null) {
	    mie = new CodeMethodInvokeExpression ();
	    mie.Method = new CodeMethodReferenceExpression (pb, "AddContextStructure");
	    mie.Parameters.Add (CDH.This);
	    apply.Statements.Add (mie);

	    foreach (string param in Structure.Parameters) {
		if (Structure[param] != StructureParameterKind.Structure)
		    continue;
		
		mie = new CodeMethodInvokeExpression ();
		mie.Method = new CodeMethodReferenceExpression (pb, "AddContextStructure");
		mie.Parameters.Add (new CodeFieldReferenceExpression (CDH.This, param));
		apply.Statements.Add (mie);
	    }
	    //}

	    foreach (BGTargetBuilder iter in targs)
		iter.EmitApply (apply, pb, tb, log);

	    foreach (string key in lits.Keys) {
		CodeExpression val = CDH.ResultExpression (lits[key]);

		CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression ();
		cmie.Method = new CodeMethodReferenceExpression (pb, "DefineConstantTarget");
		cmie.Parameters.Add (new CodePrimitiveExpression (key));
		cmie.Parameters.Add (val);
		cmie.Parameters.Add (log);

		apply.Statements.Add (CDH.IfTrueReturnTrue (cmie));
	    }
	}
		public void RegisterComponentInstanceWithKey()
		{
			MockXMLContainerBuilder containerBuilder = new MockXMLContainerBuilder(null);
			string xml = @"<component-instance key='foo'>Bar</component-instance>";

			CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
			CodeVariableReferenceExpression cvre = new CodeVariableReferenceExpression();
			containerBuilder.CallRegisterComponentInstance(ConvertToXml(xml), cmie, cvre);

			Assert.AreEqual(Constants.REGISTER_COMPONENT_INSTANCE, cmie.Method.MethodName);
			Assert.AreEqual(2, cmie.Parameters.Count);
		}
 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));
             }
         }
     }
 }
		public void Constructor1 () {
			string variableName = "mono";

			CodeVariableReferenceExpression cvre = new CodeVariableReferenceExpression (
				variableName);
			Assert.IsNotNull (cvre.VariableName, "#1");
			Assert.AreSame (variableName, cvre.VariableName, "#2");

			cvre = new CodeVariableReferenceExpression (
				(string) null);
			Assert.IsNotNull (cvre.VariableName, "#3");
			Assert.AreEqual (string.Empty, cvre.VariableName, "#4");
		}
 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);
 }
예제 #27
0
파일: ActionTree.cs 프로젝트: mono/stetic
        public void GenerateBuildCode(GeneratorContext ctx, CodeVariableReferenceExpression uiManager)
        {
            StringBuilder sb = new StringBuilder ();
            sb.Append ("<ui>");
            GenerateUiString (sb);
            sb.Append ("</ui>");

            CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression (
                uiManager,
                "AddUiFromString",
                new CodePrimitiveExpression (sb.ToString ())
            );
            ctx.Statements.Add (exp);
        }
        protected override void ParseElement(XElement element)
        {
            if (!m_firstElement)
                throw new InvalidOperationException();

            var objectParser = new ObjectParser(State);
            objectParser.Parse(element);

            var left = new CodePropertyReferenceExpression(
                new CodeVariableReferenceExpression(Parent.VariableName), Name);
            var right = new CodeVariableReferenceExpression(objectParser.VariableName);
            var assignment = new CodeAssignStatement(left, right);
            State.AddStatement(assignment);
        }
예제 #29
0
		/// <summary>
		/// Builds the Compose() method.
		/// </summary>
		public CodeMemberMethod Build(XmlElement rootNode, IList assemblies, XMLContainerBuilder.CallBack callBack)
		{
			CodeMemberMethod composeMethod = new CodeMemberMethod();
			composeMethod.Attributes = MemberAttributes.Public;
			composeMethod.ReturnType = new CodeTypeReference(typeof(IMutablePicoContainer));
			composeMethod.Name = "Compose";
			composeMethod.Statements.Add(new CodeSnippetStatement("DefaultPicoContainer p = new DefaultPicoContainer(parent);"));

			CodeVariableReferenceExpression picoContainerVariableRefr = new CodeVariableReferenceExpression("p");
			callBack(composeMethod, picoContainerVariableRefr, rootNode, assemblies); // continue reading from DOM and add as statements
			composeMethod.Statements.Add(new CodeMethodReturnStatement(picoContainerVariableRefr));

			return composeMethod;
		}
예제 #30
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;
 }
예제 #31
0
 protected override void GenerateVariableReferenceExpression(System.CodeDom.CodeVariableReferenceExpression e)
 {
     Output.Write(e.VariableName);
 }
예제 #32
0
        /// <summary>
        /// Creates an object that translates the parameters used for external methods to parameters for internal methods.
        /// </summary>
        public CreateExParameterMatrix(TableSchema tableSchema)
        {
            // Initialize the object.
            this.ExternalParameterItems = new SortedList <string, ExternalParameterItem>();
            this.CreateParameterItems   = new SortedList <string, InternalParameterItem>();
            this.UpdateParameterItems   = new SortedList <string, InternalParameterItem>();

            // Place all the columns of the table in a list that will drive the creation of parameters.  Those that columns that
            // are native to this table will be left in the list.  Those columns that are part of a foreign constraint will be
            // replace in the final argument list with internal values that can be used to look up the actual value.
            List <ColumnSchema> columnList = new List <ColumnSchema>();

            foreach (KeyValuePair <string, ColumnSchema> keyValuePair in tableSchema.Columns)
            {
                columnList.Add(keyValuePair.Value);
            }

            // The 'CreateEx' method doesn't have an explicit unique key in the parameter list like the 'Update' and 'Delete', so
            // there's no explicit input parameter to which to associate the unique row that is the target of the operation.  This
            // creates an implicit unique index which will be resolved using the explicit input parameters to this method.
            this.RowExpression       = new CodeRandomVariableReferenceExpression();
            this.UniqueKeyExpression = new CodeRandomVariableReferenceExpression();

            // Every internal update method requires a primary key specification.  This key is created from the primary key columns
            // of the existing row.  While it may seem redundant to find a row before calling the internal method to update that
            // same row, one of the primary purposes of the external method is to short-circuit the optimistic concurrency
            // checking.  To do that, the row version from the existing row is required.  The same row that provides the current
            // row version also provides the unique key to call the internal method.  However, Any one of the unique constraints
            // associated with the table can be used from the external interface to look up the row before the internal method is
            // called.  This makes it possible to change the primary key of a given column which is a requirement of a true
            // relational database model.  Said differently, this parameter item acts like the 'WHERE' clause in an SQL statement.
            InternalParameterItem primaryKeyParameterItem = new InternalParameterItem();
            List <CodeExpression> primaryKeyExpressions   = new List <CodeExpression>();

            foreach (ColumnSchema columnSchema in tableSchema.PrimaryKey.Columns)
            {
                primaryKeyExpressions.Add(new CodePropertyReferenceExpression(this.RowExpression, columnSchema.Name));
            }
            primaryKeyParameterItem.Expression = new CodeArrayCreateExpression(new CodeGlobalTypeReference(typeof(Object)), primaryKeyExpressions.ToArray());
            primaryKeyParameterItem.Name       = String.Format("{0}Key", CommonConversion.ToCamelCase(tableSchema.Name));
            this.UpdateParameterItems.Add(primaryKeyParameterItem.Name, primaryKeyParameterItem);

            // This will make sure that all the constraints on a table are satisfied by the list of parameters.
            foreach (ForeignKeyConstraintSchema foreignKeyConstraintSchema in tableSchema.ForeignKeyConstraintSchemas)
            {
                // No attempt will be made to resolve complex, redundant constraints as the same data can be found from simpler
                // ones.  The presence of the redundant, complex foreign keys will only confuse the interface.
                if (foreignKeyConstraintSchema.IsRedundant)
                {
                    continue;
                }

                // This item describes an input parameter that uses one or more external identifiers as a keys to parent tables.
                // Those parent tables provide the actual values that are used to update the record.  This allows an external
                // interface to use external identifiers from related tables.
                ForeignKeyConstraintParameterItem foreignKeyConstraintParameterItem = new ForeignKeyConstraintParameterItem();

                // This is the foreign constraint that is to be resolved with this parameter.
                foreignKeyConstraintParameterItem.ForeignKeyConstraintSchema = foreignKeyConstraintSchema;
                foreignKeyConstraintParameterItem.ActualDataType             = typeof(Object[]);
                foreignKeyConstraintParameterItem.DeclaredDataType           = typeof(Object[]);
                foreignKeyConstraintParameterItem.Description = foreignKeyConstraintParameterItem.IsNullable ?
                                                                String.Format("An optional unique key for the parent {0} record.", foreignKeyConstraintSchema.RelatedTable) :
                                                                String.Format("A required unique key for the parent {0} record.", foreignKeyConstraintSchema.RelatedTable);
                foreignKeyConstraintParameterItem.FieldDirection = FieldDirection.In;
                foreignKeyConstraintParameterItem.Name           = String.Format("{0}Key", CommonConversion.ToCamelCase(foreignKeyConstraintSchema.RelatedTable.Name));
                if (!foreignKeyConstraintSchema.IsDistinctPathToParent)
                {
                    foreignKeyConstraintParameterItem.Name += "By";
                    foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.Columns)
                    {
                        foreignKeyConstraintParameterItem.Name += columnSchema.Name;
                    }
                }
                foreignKeyConstraintParameterItem.IsNullable = true;
                foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.Columns)
                {
                    if (!columnSchema.IsNullable)
                    {
                        foreignKeyConstraintParameterItem.IsNullable = false;
                    }
                }
                this.ExternalParameterItems.Add(foreignKeyConstraintParameterItem.Name, foreignKeyConstraintParameterItem);

                // This constructs a mapping between the foreign key parameter that is provided to the external method and the
                // individual parameters that are needed by the internal method.
                foreach (ColumnSchema columnSchema in foreignKeyConstraintSchema.Columns)
                {
                    // This creates an intermediate variable to hold a value collected from the foreign keys.  When creating an
                    // object, the required values are strongly typed.  Optional columns and columns with defaults are defined as
                    // generic types so they can be nulled if no cooresponding value is provided.
                    ForeignKeyVariableItem foreignKeyVariableItem = new ForeignKeyVariableItem();
                    foreignKeyVariableItem.ColumnSchema = columnSchema;
                    foreignKeyVariableItem.DataType     = columnSchema.IsNullable || columnSchema.DefaultValue != DBNull.Value ? typeof(Object) : columnSchema.DataType;
                    foreignKeyVariableItem.Expression   = new CodeRandomVariableReferenceExpression();
                    foreignKeyConstraintParameterItem.ForeignKeyVariables.Add(foreignKeyVariableItem);

                    // This creates an internal parameter for the 'Create' method from the elements of the foreign key.
                    InternalParameterItem createParameterItem = new InternalParameterItem();
                    createParameterItem.ColumnSchema = columnSchema;
                    createParameterItem.Expression   = foreignKeyVariableItem.Expression;
                    createParameterItem.Name         = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.CreateParameterItems.Add(createParameterItem.Name, createParameterItem);

                    // This creates an internal parameter for the 'Update' method from the elements of the foreign key.
                    InternalParameterItem updateParameterItem = new InternalParameterItem();
                    updateParameterItem.ColumnSchema = columnSchema;
                    updateParameterItem.Expression   = foreignKeyVariableItem.Expression;
                    updateParameterItem.Name         = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.UpdateParameterItems.Add(updateParameterItem.Name, updateParameterItem);

                    // Any items resolved using foreign constraints are removed from the list of input parameters.  The key is the
                    // means of evaluating the column's value and it can't be added directly from the outside world.
                    columnList.Remove(columnSchema);
                }
            }

            // At this point, all the parameters that need to be resolved with foreign keys have been added to the list of external
            // and internal parameters and their related columns have been removed from the list of input parameters.  This next
            // block will add the remaining items to the list of external and internal parameters.
            foreach (ColumnSchema columnSchema in columnList)
            {
                // If a column requires special processing, it is not handled with the rest of the parameters.
                bool isOrdinaryColumn = true;

                // Since the external world doesn't have access to the row versions, they must be removed from the input
                // parameters.  A mechanism is constructed internal to the method to defeat the optimistic concurrency checking.
                if (columnSchema.IsRowVersion)
                {
                    // This is no ordinary column.
                    isOrdinaryColumn = false;

                    // This parameters is used for the internal 'Update' methods to defeat the optimistic concurrency checking.  It is not
                    // part of the 'Create' interface.
                    InternalParameterItem internalParameterItem = new InternalParameterItem();
                    internalParameterItem.ColumnSchema = columnSchema;
                    internalParameterItem.Expression   = new CodePropertyReferenceExpression(this.RowExpression, "RowVersion");
                    internalParameterItem.Name         = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.UpdateParameterItems.Add(internalParameterItem.Name, internalParameterItem);
                }

                // AutoIncremented columns can only be specified as output parameters.
                if (columnSchema.IsAutoIncrement)
                {
                    // This is no ordinary column.
                    isOrdinaryColumn = false;

                    // Create an outpt parameter for the AutoIncremented values as the values are always generated by the middle
                    // tier.
                    SimpleParameterItem simpleParameterItem = new SimpleParameterItem();
                    simpleParameterItem.ActualDataType   = columnSchema.DataType;
                    simpleParameterItem.ColumnSchema     = columnSchema;
                    simpleParameterItem.DeclaredDataType = columnSchema.DataType;
                    simpleParameterItem.Description      = String.Format("The output value for the {0} column.", columnSchema.Name);
                    simpleParameterItem.Name             = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.ExternalParameterItems.Add(simpleParameterItem.Name, simpleParameterItem);

                    // Note that when an object with an AutoIncrement column is added, the column is specified as an output
                    // parameter.
                    InternalParameterItem createParameterItem = new InternalParameterItem();
                    createParameterItem.ColumnSchema = columnSchema;
                    createParameterItem.Expression   = new CodeDirectionExpression(FieldDirection.Out, new CodeArgumentReferenceExpression(simpleParameterItem.Name));
                    createParameterItem.Name         = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.CreateParameterItems.Add(createParameterItem.Name, createParameterItem);

                    // The AutoIncrement column is a simple input parameter when the record is updated.
                    InternalParameterItem updateParameterItem = new InternalParameterItem();
                    updateParameterItem.ColumnSchema = columnSchema;
                    updateParameterItem.Expression   = new CodeArgumentReferenceExpression(simpleParameterItem.Name);
                    updateParameterItem.Name         = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.UpdateParameterItems.Add(updateParameterItem.Name, updateParameterItem);
                }

                // Ordinary parameters are passed from the external caller to the internal methods without modification or
                // interpretation.
                if (isOrdinaryColumn)
                {
                    // Create a simple input parameter from the column information.  The only complication is whether the value
                    // must be provided by the caller or is optional.
                    SimpleParameterItem simpleParameterItem = new SimpleParameterItem();
                    bool isOptional = columnSchema.IsNullable || columnSchema.DefaultValue != DBNull.Value;
                    simpleParameterItem.ActualDataType   = columnSchema.DataType;
                    simpleParameterItem.ColumnSchema     = columnSchema;
                    simpleParameterItem.DeclaredDataType = isOptional ? typeof(Object) : columnSchema.DataType;
                    simpleParameterItem.Description      = String.Format("The {0} value for the {1} column.", isOptional ? "optional" : "required", CommonConversion.ToCamelCase(columnSchema.Name));
                    simpleParameterItem.FieldDirection   = FieldDirection.In;
                    simpleParameterItem.Name             = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.ExternalParameterItems.Add(simpleParameterItem.Name, simpleParameterItem);

                    // This is how the parameter will be interpreted by the 'Insert' and 'Update' internal methods.
                    InternalParameterItem internalParameterItem = new InternalParameterItem();
                    internalParameterItem.ColumnSchema = columnSchema;
                    internalParameterItem.Expression   = new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name));
                    internalParameterItem.Name         = CommonConversion.ToCamelCase(columnSchema.Name);
                    this.CreateParameterItems.Add(internalParameterItem.Name, internalParameterItem);
                    this.UpdateParameterItems.Add(internalParameterItem.Name, internalParameterItem);
                }
            }

            // A configuration identifier is is required on all interface methods except the 'Configuration' table.  While not
            // every method requires the resolution of multiple external keys, the decision to add this for column was made for
            // consistency.  The idea that the external interface shouldn't break if a new unique key is added to the hierarchy.
            // This means more work up front to configure the external interfaces, but it means less work later on as the relations
            // and schema change.
            if (tableSchema.Name != "Configuration")
            {
                ExternalParameterItem externalParameterItem = new ExternalParameterItem();
                externalParameterItem.ActualDataType   = typeof(String);
                externalParameterItem.DeclaredDataType = typeof(String);
                externalParameterItem.Description      = "Selects a configuration of unique indices used to resolve external identifiers.";
                externalParameterItem.FieldDirection   = FieldDirection.In;
                externalParameterItem.IsNullable       = false;
                externalParameterItem.Name             = "configurationId";
                this.ExternalParameterItems.Add(externalParameterItem.Name, externalParameterItem);
            }
        }