Inheritance: System.CodeDom.CodeExpression
コード例 #1
0
		public void Constructor1 ()
		{
			CodeExpression expression = new CodeExpression ();
			CodeTypeReference type = new CodeTypeReference ("mono");
			string methodName = "mono";

			CodeDelegateCreateExpression cdce = new CodeDelegateCreateExpression (
				type, expression, methodName);

			Assert.IsNotNull (cdce.DelegateType, "#1");
			Assert.AreSame (type, cdce.DelegateType, "#2");
			Assert.IsNotNull (cdce.MethodName, "#3");
			Assert.AreSame (methodName, cdce.MethodName, "#4");
			Assert.IsNotNull (cdce.TargetObject, "#5");
			Assert.AreSame (expression, cdce.TargetObject, "#6");

			cdce = new CodeDelegateCreateExpression ((CodeTypeReference) null,
				(CodeExpression) null, (string) null);

			Assert.IsNotNull (cdce.DelegateType, "#7");
			Assert.AreEqual (typeof (void).FullName, cdce.DelegateType.BaseType, "#8");
			Assert.IsNotNull (cdce.MethodName, "#9");
			Assert.AreEqual (string.Empty, cdce.MethodName, "#10");
			Assert.IsNull (cdce.TargetObject, "#11");
		}
 internal static CodeMemberMethod AddAsyncMethod(CodeTypeDeclaration codeClass, string methodName, string[] parameterTypeNames, string[] parameterNames, string callbackMember, string callbackName, string userState)
 {
     CodeMemberMethod method = AddMethod(codeClass, methodName, new CodeFlags[parameterNames.Length], parameterTypeNames, parameterNames, typeof(void).FullName, null, CodeFlags.IsPublic);
     method.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), methodName, new CodeExpression[0]);
     for (int i = 0; i < parameterNames.Length; i++)
     {
         expression.Parameters.Add(new CodeArgumentReferenceExpression(parameterNames[i]));
     }
     expression.Parameters.Add(new CodePrimitiveExpression(null));
     method.Statements.Add(expression);
     method = AddMethod(codeClass, methodName, new CodeFlags[parameterNames.Length], parameterTypeNames, parameterNames, typeof(void).FullName, null, CodeFlags.IsPublic);
     method.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userState));
     CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), callbackMember);
     CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
     CodeDelegateCreateExpression right = new CodeDelegateCreateExpression {
         DelegateType = new CodeTypeReference(typeof(SendOrPostCallback)),
         TargetObject = new CodeThisReferenceExpression(),
         MethodName = callbackName
     };
     CodeStatement[] trueStatements = new CodeStatement[] { new CodeAssignStatement(left, right) };
     method.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[0]));
     return method;
 }
コード例 #3
0
		public override void Serialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
		{
			if (statements == null)
				throw new ArgumentNullException ("statements");
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");
			if (descriptor == null)
				throw new ArgumentNullException ("descriptor");

			IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService;
			if (service != null) {
				// In the propertygrid the events are represented by PropertyDescriptors and the value is a string
				// which contains the method name to bind to. The propertydescriptors are managed and created by the 
				// IEventBindingService
				// 
				EventDescriptor ev = (EventDescriptor) descriptor;
				string methodName = (string) service.GetEventProperty (ev).GetValue (value);
				CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression (new CodeTypeReference (ev.EventType), _thisReference, methodName);
				CodeExpression targetObject = base.SerializeToExpression (manager, value);
				CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression (targetObject, ev.Name);
				statements.Add (new CodeAttachEventStatement (eventRef, listener));
			}
		}
コード例 #4
0
		public override void Serialize (IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, 
						CodeStatementCollection statements)
		{
			if (statements == null)
				throw new ArgumentNullException ("statements");
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");
			if (descriptor == null)
				throw new ArgumentNullException ("descriptor");

			IEventBindingService service = manager.GetService (typeof (IEventBindingService)) as IEventBindingService;
			if (service != null) {
				EventDescriptor eventDescriptor = (EventDescriptor) descriptor;
				string methodName = (string) service.GetEventProperty (eventDescriptor).GetValue (value);

				if (methodName != null) {
					CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression (new CodeTypeReference (eventDescriptor.EventType),
																							   _thisReference, methodName);
					CodeExpression targetObject = base.SerializeToExpression (manager, value);
					CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression (targetObject, eventDescriptor.Name);
					statements.Add (new CodeAttachEventStatement (eventRef, listener));
				}
			}
		}
コード例 #5
0
 public TypescriptDelegateCreateExpression(
     IExpressionFactory expressionFactory,
     CodeDelegateCreateExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptDelegateCreateExpression Created");
 }
コード例 #6
0
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeDelegateCreateExpression cdce = new CodeDelegateCreateExpression ();
			Assert.AreEqual ("System.Void", cdce.DelegateType.BaseType, "DelegateType");
			cdce.DelegateType = new CodeTypeReference ("System.Int32");
			Assert.AreEqual (String.Empty, cdce.MethodName, "MethodName");
			cdce.MethodName = "mono";
			Assert.IsNull (cdce.TargetObject, "TargetObject");
			cdce.TargetObject = new CodeExpression ();
		}
 public static CodeDelegateCreateExpression Clone(this CodeDelegateCreateExpression expression)
 {
     if (expression == null) return null;
     CodeDelegateCreateExpression e = new CodeDelegateCreateExpression();
     e.DelegateType = expression.DelegateType.Clone();
     e.MethodName = expression.MethodName;
     e.TargetObject = expression.TargetObject.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
コード例 #8
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeTypeReference delegate_type = new CodeTypeReference ("System.Int32");
			CodeExpression target = new CodeExpression ();
			string method = "mono";
			CodeDelegateCreateExpression cdce = new CodeDelegateCreateExpression (delegate_type, target, method);
			Assert.AreSame (delegate_type, cdce.DelegateType, "DelegateType");
			cdce.DelegateType = new CodeTypeReference ("System.Void");
			Assert.AreEqual (method, cdce.MethodName, "MethodName");
			cdce.MethodName = String.Empty;
			Assert.AreSame (target, cdce.TargetObject, "TargetObject");
			cdce.TargetObject = new CodeExpression ();
		}
 public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
 {
     EventDescriptor e = descriptor as EventDescriptor;
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     if (e == null)
     {
         throw new ArgumentNullException("descriptor");
     }
     if (statements == null)
     {
         throw new ArgumentNullException("statements");
     }
     try
     {
         IEventBindingService service = (IEventBindingService) manager.GetService(typeof(IEventBindingService));
         if (service != null)
         {
             string methodName = (string) service.GetEventProperty(e).GetValue(value);
             if (methodName != null)
             {
                 CodeExpression targetObject = base.SerializeToExpression(manager, value);
                 if (targetObject != null)
                 {
                     CodeTypeReference delegateType = new CodeTypeReference(e.EventType);
                     CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(delegateType, _thisRef, methodName);
                     CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(targetObject, e.Name);
                     CodeAttachEventStatement statement = new CodeAttachEventStatement(eventRef, listener);
                     statement.UserData[typeof(Delegate)] = e.EventType;
                     statements.Add(statement);
                 }
             }
         }
     }
     catch (Exception innerException)
     {
         if (innerException is TargetInvocationException)
         {
             innerException = innerException.InnerException;
         }
         manager.ReportError(System.Design.SR.GetString("SerializerPropertyGenFailed", new object[] { e.Name, innerException.Message }));
     }
 }
コード例 #10
0
        public void Visit(ProcedureCall call)
        {
            var domArg = new CodeDomArg();

            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "Exec_" + domArg.MethodIdentifier;
            method.Attributes = MemberAttributes.Private;
            GenerateCallStatement(method.Statements, call.Line.Line);
            _mainType.Type.Members.Add(method);

            var methodStatements = new CodeStatementCollection();

            var argList = new List<CodeExpression>();
            foreach(var arg in call.Args)
            {
                domArg = VisitChild(arg);
                argList.Add(domArg.CodeExpression);
            }

            methodStatements.Add(
                new CodeVariableDeclarationStatement(call.Name, "r",
                    new CodeObjectCreateExpression(call.Name, argList.ToArray()))
                    );

            methodStatements.Add(
            new CodeAssignStatement(
                new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("r"), "RequestFactory"),
                new CodePropertyReferenceExpression(null, "RequestFactory"))
                );

            var delegateGen = new CodeDelegateCreateExpression(new CodeTypeReference(typeof(Action<ProgressArgs>)),
                new CodeThisReferenceExpression(), "OnProgress");
            methodStatements.Add(new CodeAttachEventStatement(new CodeVariableReferenceExpression("r"), "Progress", delegateGen));

            methodStatements.Add(
                new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("r"), "Run")
            );

            methodStatements.Add(new CodeRemoveEventStatement(new CodeVariableReferenceExpression("r"), "Progress", delegateGen));

            method.Statements.AddRange(methodStatements);

            var methodcall = new CodeMethodInvokeExpression(
              new CodeMethodReferenceExpression(null, method.Name));
            _codeStack.Peek().ParentStatements.Add(methodcall);
        }
 private CodeStatement BuildControlSkinAssignmentStatement(ControlBuilder builder, string skinID)
 {
     Type controlType = builder.ControlType;
     string name = base.GetMethodNameForBuilder(BaseTemplateCodeDomTreeGenerator.buildMethodPrefix, builder) + "_skinKey";
     CodeMemberField field = new CodeMemberField(typeof(object), name) {
         Attributes = MemberAttributes.Private | MemberAttributes.Static
     };
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(PageTheme)), "CreateSkinKey")
     };
     expression.Parameters.Add(new CodeTypeOfExpression(controlType));
     expression.Parameters.Add(new CodePrimitiveExpression(skinID));
     field.InitExpression = expression;
     base._sourceDataClass.Members.Add(field);
     CodeFieldReferenceExpression targetObject = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "__controlSkins");
     CodeIndexerExpression left = new CodeIndexerExpression(targetObject, new CodeExpression[] { new CodeVariableReferenceExpression(name) });
     CodeDelegateCreateExpression expression4 = new CodeDelegateCreateExpression(this._controlSkinDelegateType, new CodeThisReferenceExpression(), base.GetMethodNameForBuilder(BaseTemplateCodeDomTreeGenerator.buildMethodPrefix, builder));
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(this._controlSkinType, new CodeExpression[0]);
     right.Parameters.Add(new CodeTypeOfExpression(controlType));
     right.Parameters.Add(expression4);
     return new CodeAssignStatement(left, right);
 }
コード例 #12
0
ファイル: VBCodeGenerator.cs プロジェクト: nlhepler/mono
		protected override void GenerateDelegateCreateExpression (CodeDelegateCreateExpression expression)
		{
			TextWriter output = Output;

			output.Write ("AddressOf ");

			CodeExpression targetObject = expression.TargetObject;
			if (targetObject != null) {
				GenerateExpression (targetObject);
				Output.Write ('.');
			}
			output.Write (expression.MethodName);
		}
コード例 #13
0
ファイル: CodeGenerator.cs プロジェクト: carrie901/mono
		protected abstract void GenerateDelegateCreateExpression (CodeDelegateCreateExpression e);
コード例 #14
0
ファイル: CodeGenerator.cs プロジェクト: carrie901/mono
			public void Visit (CodeDelegateCreateExpression o)
			{
				g.GenerateDelegateCreateExpression (o);
			}
コード例 #15
0
		internal static void BindSignalHandlers (CodeExpression targetObjectVar, ObjectWrapper wrapper, Stetic.WidgetMap map, CodeStatementCollection statements, GenerationOptions options)
		{
			foreach (Signal signal in wrapper.Signals) {
				SignalDescriptor descriptor = signal.SignalDescriptor;
				
				CodeExpression createDelegate;
				
				if (options.UsePartialClasses) {
					createDelegate =
						new CodeDelegateCreateExpression (
							new CodeTypeReference (descriptor.HandlerTypeName, CodeTypeReferenceOptions.GlobalReference),
							new CodeThisReferenceExpression (),
							signal.Handler);
				} else {
					createDelegate =
						new CodeMethodInvokeExpression (
							new CodeTypeReferenceExpression (new CodeTypeReference (typeof(Delegate), CodeTypeReferenceOptions.GlobalReference)),
							"CreateDelegate",
							new CodeTypeOfExpression (descriptor.HandlerTypeName),
							targetObjectVar,
							new CodePrimitiveExpression (signal.Handler));
					
					createDelegate = new CodeCastExpression (descriptor.HandlerTypeName.ToGlobalTypeRef (), createDelegate);
				}
				
				CodeAttachEventStatement cevent = new CodeAttachEventStatement (
					new CodeEventReferenceExpression (
						map.GetWidgetExp (wrapper),
						descriptor.Name),
					createDelegate);
				
				statements.Add (cevent);
			}
			
			Wrapper.Widget widget = wrapper as Wrapper.Widget;
			if (widget != null && widget.IsTopLevel) {
				// Bind local action signals
				foreach (Wrapper.ActionGroup grp in widget.LocalActionGroups) {
					foreach (Wrapper.Action ac in grp.Actions)
						BindSignalHandlers (targetObjectVar, ac, map, statements, options);
				}
			}
			
			Gtk.Container cont = wrapper.Wrapped as Gtk.Container;
			if (cont != null) {
				foreach (Gtk.Widget child in cont.AllChildren) {
					Stetic.Wrapper.Widget ww = Stetic.Wrapper.Widget.Lookup (child);
					if (ww != null)
						BindSignalHandlers (targetObjectVar, ww, map, statements, options);
				}
			}
			
		}
コード例 #16
0
        public override object Serialize(IDesignerSerializationManager manager, object obj)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");

            if (manager.Context == null)
                throw new ArgumentException("manager", SR.GetString(SR.Error_MissingContextProperty));

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

            DependencyObject dependencyObject = obj as DependencyObject;
            if (dependencyObject == null)
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "obj");

            Activity activity = obj as Activity;
            if (activity != null)
                manager.Context.Push(activity);

            CodeStatementCollection retVal = null;
            try
            {
                if (activity != null)
                {
                    CodeDomSerializer componentSerializer = manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)) as CodeDomSerializer;
                    if (componentSerializer == null)
                        throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(CodeDomSerializer).FullName));
                    retVal = componentSerializer.Serialize(manager, activity) as CodeStatementCollection;
                }
                else
                {
                    retVal = base.Serialize(manager, obj) as CodeStatementCollection;
                }

                if (retVal != null)
                {
                    CodeStatementCollection codeStatements = new CodeStatementCollection(retVal);
                    CodeExpression objectExpression = SerializeToExpression(manager, obj);
                    if (objectExpression != null)
                    {
                        ArrayList propertiesSerialized = new ArrayList();
                        List<DependencyProperty> dependencyProperties = new List<DependencyProperty>(dependencyObject.MetaDependencyProperties);
                        foreach (DependencyProperty dp in dependencyObject.DependencyPropertyValues.Keys)
                        {
                            if (dp.IsAttached)
                            {
                                if ((dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) ||
                                    (!dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null))
                                    dependencyProperties.Add(dp);
                            }
                        }
                        foreach (DependencyProperty dependencyProperty in dependencyProperties)
                        {
                            object value = null;
                            if (dependencyObject.IsBindingSet(dependencyProperty))
                                value = dependencyObject.GetBinding(dependencyProperty);
                            else if (!dependencyProperty.IsEvent)
                                value = dependencyObject.GetValue(dependencyProperty);
                            else
                                value = dependencyObject.GetHandler(dependencyProperty);
                            // Attached property should always be set through SetValue, no matter if it's a meta property or if there is a data context.
                            // Other meta properties will be directly assigned.
                            // Other instance property will go through SetValue if there is a data context or if it's of type Bind.
                            if (value != null &&
                                (dependencyProperty.IsAttached || (!dependencyProperty.DefaultMetadata.IsMetaProperty && value is ActivityBind)))
                            {
                                object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
                                if (attributes.Length > 0)
                                {
                                    DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute;
                                    if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden)
                                        continue;
                                }

                                // Events of type Bind will go through here.  Regular events will go through IEventBindingService.
                                CodeExpression param1 = null;
                                string dependencyPropertyName = dependencyProperty.Name + ((dependencyProperty.IsEvent) ? "Event" : "Property");
                                FieldInfo fieldInfo = dependencyProperty.OwnerType.GetField(dependencyPropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                                if (fieldInfo != null && !fieldInfo.IsPublic)
                                    param1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(DependencyProperty)), "FromName", new CodePrimitiveExpression(dependencyProperty.Name), new CodeTypeOfExpression(dependencyProperty.OwnerType));
                                else
                                    param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dependencyProperty.OwnerType), dependencyPropertyName);

                                CodeExpression param2 = SerializeToExpression(manager, value);

                                //Fields property fails to serialize to expression due to reference not being created,
                                //the actual code for fields are generated in datacontext code generator so we do nothing here
                                if (param1 != null && param2 != null)
                                {
                                    CodeMethodInvokeExpression codeMethodInvokeExpr = null;
                                    if (value is ActivityBind)
                                        codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, "SetBinding", new CodeExpression[] { param1, new CodeCastExpression(new CodeTypeReference(typeof(ActivityBind)), param2) });
                                    else
                                        codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, (dependencyProperty.IsEvent) ? "AddHandler" : "SetValue", new CodeExpression[] { param1, param2 });
                                    retVal.Add(codeMethodInvokeExpr);

                                    // Remove the property set statement for the event which is replaced by the SetValue() expression.
                                    foreach (CodeStatement statement in codeStatements)
                                    {
                                        if (statement is CodeAssignStatement && ((CodeAssignStatement)statement).Left is CodePropertyReferenceExpression)
                                        {
                                            CodePropertyReferenceExpression prop = ((CodeAssignStatement)statement).Left as CodePropertyReferenceExpression;
                                            if (prop.PropertyName == dependencyProperty.Name && prop.TargetObject.Equals(objectExpression))
                                                retVal.Remove(statement);
                                        }
                                    }
                                }

                                propertiesSerialized.Add(dependencyProperty);
                            }
                        }

                        IEventBindingService eventBindingService = manager.GetService(typeof(IEventBindingService)) as IEventBindingService;
                        if (eventBindingService == null)
                        {
                            // At compile time, we don't have an event binding service.  We need to mannually emit the code to add
                            // event handlers.
                            foreach (EventDescriptor eventDesc in TypeDescriptor.GetEvents(dependencyObject))
                            {
                                string handler = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, eventDesc.Name);
                                if (!string.IsNullOrEmpty(handler))
                                {
                                    CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(objectExpression, eventDesc.Name);
                                    CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(new CodeTypeReference(eventDesc.EventType), new CodeThisReferenceExpression(), handler);
                                    retVal.Add(new CodeAttachEventStatement(eventRef, listener));
                                }
                            }
                        }

                        // We also need to handle properties of type System.Type.  If the value is a design time type, xomlserializer 
                        // is not going to be able to deserialize the type.  We then store the type name in the user data and
                        // output a "typeof(xxx)" expression using the type name w/o validating the type.
                        if (dependencyObject.UserData.Contains(UserDataKeys.DesignTimeTypeNames))
                        {
                            Hashtable typeNames = dependencyObject.UserData[UserDataKeys.DesignTimeTypeNames] as Hashtable;
                            foreach (object key in typeNames.Keys)
                            {
                                string propName = null;
                                string ownerTypeName = null;
                                string typeName = typeNames[key] as string;
                                DependencyProperty dependencyProperty = key as DependencyProperty;
                                if (dependencyProperty != null)
                                {
                                    if (propertiesSerialized.Contains(dependencyProperty))
                                        continue;

                                    object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
                                    if (attributes.Length > 0)
                                    {
                                        DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute;
                                        if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden)
                                            continue;
                                    }

                                    propName = dependencyProperty.Name;
                                    ownerTypeName = dependencyProperty.OwnerType.FullName;
                                }
                                else if (key is string)
                                {
                                    int indexOfDot = ((string)key).LastIndexOf('.');
                                    Debug.Assert(indexOfDot != -1, "Wrong property name in DesignTimeTypeNames hashtable.");
                                    if (indexOfDot != -1)
                                    {
                                        ownerTypeName = ((string)key).Substring(0, indexOfDot);
                                        propName = ((string)key).Substring(indexOfDot + 1);
                                    }
                                }

                                if (!string.IsNullOrEmpty(typeName) && !string.IsNullOrEmpty(propName) && !string.IsNullOrEmpty(ownerTypeName))
                                {
                                    if (ownerTypeName == obj.GetType().FullName)
                                    {
                                        // Property is not an attached property.  Serialize using regular property set expression.
                                        CodePropertyReferenceExpression propertyRef = new CodePropertyReferenceExpression(objectExpression, propName);
                                        retVal.Add(new CodeAssignStatement(propertyRef, new CodeTypeOfExpression(typeName)));
                                    }
                                    else
                                    {
                                        // This is an attached property.  Serialize using SetValue() expression.
                                        CodeExpression param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(ownerTypeName), propName + "Property");
                                        CodeExpression param2 = new CodeTypeOfExpression(typeName);
                                        retVal.Add(new CodeMethodInvokeExpression(objectExpression, "SetValue", new CodeExpression[] { param1, param2 }));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (activity != null)
                {
                    object pushedActivity = manager.Context.Pop();
                    System.Diagnostics.Debug.Assert(pushedActivity == activity);
                }
            }

            return retVal;
        }
コード例 #17
0
        public void GenerateProperties(CodeTypeDeclaration ctd, ClassInfo ci)
        {
            CodeMemberProperty prop;

            foreach (FieldInfo fi in classInfo.LocalFields)
            {
                if (fi.References != null)
                    continue;

                if (fi.IsNullable)
                {
                    if (options.NullableRepresentation == PrimitiveRepresentation.RawWithIsNull)
                    {
                        ctd.Members.Add(_IsNull(fi));
                        if (!ci.ReadOnly)
                        {
                            ctd.Members.Add(_SetNull(fi));
                        }
                    }
                }
                else
                {
                    if (options.NotNullRepresentation == PrimitiveRepresentation.RawWithIsNull)
                    {
                        if (!ci.ReadOnly)
                        {
                            // if it's read-only, not-null means not-null and there's no
                            // exception
                            ctd.Members.Add(_IsNull(fi));
                        }
                    }
                }
            }

            int primaryKeyComponentNumber = 0;

            foreach (FieldInfo fi in classInfo.LocalFields)
            {
                PrimitiveRepresentation actualNullableRepresentation = options.NullableRepresentation;
                PrimitiveRepresentation actualNotNullRepresentation = options.NotNullRepresentation;

                if (fi.GetNullableFieldHandler().GetSqlType() == null)
                {
                    if (actualNotNullRepresentation == PrimitiveRepresentation.SqlType)
                        actualNotNullRepresentation = PrimitiveRepresentation.Raw;

                    if (actualNullableRepresentation == PrimitiveRepresentation.SqlType)
                        actualNullableRepresentation = PrimitiveRepresentation.Raw;
                }

                CodeTypeReference returnType;

                //if (fi.Name == ci.PrimaryKeyFieldName)
                //{
                //  returnType = GetReturnType(PrimitiveRepresentation.Raw, fi.DataType);
                //}
                //else
                if (fi.References != null)
                {
                    returnType = new CodeTypeReference(fi.References);
                }
                else if (fi.IsNullable)
                {
                    returnType = GetReturnType(actualNullableRepresentation, fi);
                }
                else
                {
                    returnType = GetReturnType(actualNotNullRepresentation, fi);
                }

                prop = new CodeMemberProperty();
                prop.Name = fi.Name;
                prop.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                prop.Type = returnType;
                //prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, "_FieldNames")));
                if (fi.Description != null)
                {
                    prop.Comments.Add(new CodeCommentStatement("<summary>", true));
                    prop.Comments.Add(new CodeCommentStatement(fi.Description, true));
                    prop.Comments.Add(new CodeCommentStatement("</summary>", true));
                }
                ctd.Members.Add(prop);

                if (fi.Size != -1)
                {
                    CodeAttributeDeclaration cad = new CodeAttributeDeclaration("Sooda.SoodaFieldSizeAttribute");
                    cad.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(fi.Size)));
                    prop.CustomAttributes.Add(cad);
                }

                if (fi.IsPrimaryKey)
                {
                    CodeExpression getPrimaryKeyValue = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetPrimaryKeyValue");

                    if (classInfo.GetPrimaryKeyFields().Length > 1)
                    {
                        getPrimaryKeyValue = new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(SoodaTuple)), "GetValue", getPrimaryKeyValue, new CodePrimitiveExpression(primaryKeyComponentNumber));
                    }

                    if (fi.References != null)
                    {
                        prop.GetStatements.Add(
                            new CodeMethodReturnStatement(
                            new CodeMethodInvokeExpression(
                                LoaderClass(fi.ReferencedClass),
                                "GetRef",
                                GetTransaction(),
                                new CodeCastExpression(
                                    GetReturnType(actualNotNullRepresentation, fi),
                                    getPrimaryKeyValue
                            ))));
                    }
                    else
                    {
                        prop.GetStatements.Add(
                            new CodeMethodReturnStatement(
                            new CodeCastExpression(
                            prop.Type,
                            getPrimaryKeyValue
                            )));
                    }

                    if (!classInfo.ReadOnly && !fi.ReadOnly)
                    {
                        if (classInfo.GetPrimaryKeyFields().Length == 1)
                        {
                            prop.SetStatements.Add(
                                new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(), "SetPrimaryKeyValue",
                                new CodePropertySetValueReferenceExpression())));
                        }
                        else
                        {
                            CodeExpression plainValue = new CodePropertySetValueReferenceExpression();
                            if (fi.References != null)
                                plainValue = new CodeMethodInvokeExpression(plainValue, "GetPrimaryKeyValue");
                            prop.SetStatements.Add(
                                new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(), "SetPrimaryKeySubValue",
                                plainValue,
                                new CodePrimitiveExpression(primaryKeyComponentNumber),
                                new CodePrimitiveExpression(classInfo.GetPrimaryKeyFields().Length))));
                        }
                    }
                    primaryKeyComponentNumber++;
                    continue;
                }

                if (options.NullPropagation && (fi.References != null || fi.IsNullable) && actualNullableRepresentation != PrimitiveRepresentation.Raw)
                {
                    CodeExpression retVal = new CodePrimitiveExpression(null);

                    if (fi.References == null && actualNullableRepresentation == PrimitiveRepresentation.SqlType)
                    {
                        retVal = new CodePropertyReferenceExpression(
                            new CodeTypeReferenceExpression(fi.GetNullableFieldHandler().GetSqlType()), "Null");
                    }

                    prop.GetStatements.Add(
                        new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                        new CodeThisReferenceExpression(),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)),
                        new CodeStatement[]
                            {
                                new CodeMethodReturnStatement(retVal)
                            },
                        new CodeStatement[]
                            {
                            }));
                }

                if (fi.References != null)
                {
                    // reference field getter
                    //
                    CodeExpression pk = new CodeVariableReferenceExpression("pk");
                    Type pkType;
                    CodeExpression isFieldNotNull;
                    CodeExpression getRef;
                    if (fi.ParentClass.GetDataSource().EnableDynamicFields)
                    {
                        pkType = typeof(object);
                        isFieldNotNull = new CodeBinaryOperatorExpression(
                            pk,
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodePrimitiveExpression(null));
                        getRef = new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(SoodaObject)),
                            "GetRefHelper",
                            GetTransaction(),
                            Factory(fi.References),
                            pk);
                    }
                    else
                    {
                        pkType = fi.GetNullableFieldHandler().GetSqlType();
                        isFieldNotNull = new CodeBinaryOperatorExpression(
                            new CodePropertyReferenceExpression(pk, "IsNull"),
                            CodeBinaryOperatorType.ValueEquality,
                            new CodePrimitiveExpression(false));
                        getRef = new CodeMethodInvokeExpression(
                            LoaderClass(fi.ReferencedClass),
                            "GetRef",
                            GetTransaction(),
                            new CodePropertyReferenceExpression(pk, "Value"));
                    }
                    prop.GetStatements.Add(
                            new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(
                                    RefCacheExpression(ci, fi),
                                    CodeBinaryOperatorType.IdentityEquality,
                                    new CodePrimitiveExpression(null)),
                                new CodeStatement[]
                                {
                                new CodeVariableDeclarationStatement(pkType, "pk", GetFieldValueForRead(fi)),
                                new CodeConditionStatement(
                                    isFieldNotNull,
                                    new CodeStatement[]
                                    {
                                    new CodeAssignStatement(
                                        RefCacheExpression(ci, fi),
                                        getRef)
                                    })
                                }
                    ));


                    prop.GetStatements.Add(
                            new CodeMethodReturnStatement(
                                new CodeCastExpression(returnType,
                                    RefCacheExpression(ci, fi))));

                    // reference field setter
                    if (!classInfo.ReadOnly && !fi.ReadOnly)
                    {
                        prop.SetStatements.Add(
                                new CodeExpressionStatement(

                                    new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(typeof(Sooda.ObjectMapper.SoodaObjectImpl)), "SetRefFieldValue",

                                        // parameters
                                        new CodeThisReferenceExpression(),
                                        new CodePrimitiveExpression(fi.Table.OrdinalInClass),
                                        new CodePrimitiveExpression(fi.Name),
                                        new CodePrimitiveExpression(fi.ClassUnifiedOrdinal),
                                        new CodePropertySetValueReferenceExpression(),
                                        RefCacheArray(),
                                        new CodePrimitiveExpression(GetFieldRefCacheIndex(ci, fi)),
                                        Factory(returnType.BaseType)
                                        )));
                    }
                }
                else
                {
                    // plain field getter

                    CodeExpression fieldValue = GetFieldValueForRead(fi);
                    if (fi.ParentClass.GetDataSource().EnableDynamicFields)
                    {
                        switch (fi.IsNullable ? actualNullableRepresentation : actualNotNullRepresentation)
                        {
                            case PrimitiveRepresentation.Boxed:
                                break;

                            case PrimitiveRepresentation.SqlType:
                            case PrimitiveRepresentation.RawWithIsNull:
                            case PrimitiveRepresentation.Raw:
                                fieldValue = new CodeCastExpression(new CodeTypeReference(fi.GetNullableFieldHandler().GetFieldType()), fieldValue);
                                break;

                            case PrimitiveRepresentation.Nullable:
                                fieldValue = new CodeCastExpression(new CodeTypeReference(fi.GetNullableFieldHandler().GetNullableType()), fieldValue);
                                break;

                            default:
                                throw new NotImplementedException("Unknown PrimitiveRepresentation");
                        }
                    }
                    prop.GetStatements.Add(new CodeMethodReturnStatement(fieldValue));

                    if (!classInfo.ReadOnly && !fi.ReadOnly)
                    {
                        // plain field setter

                        CodeExpression beforeDelegate = new CodePrimitiveExpression(null);
                        CodeExpression afterDelegate = new CodePrimitiveExpression(null);

                        if (classInfo.Triggers)
                        {
                            beforeDelegate = new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SoodaFieldUpdateDelegate)),
                                    new CodeThisReferenceExpression(), "BeforeFieldUpdate_" + fi.Name);
                            afterDelegate = new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SoodaFieldUpdateDelegate)),
                                    new CodeThisReferenceExpression(), "AfterFieldUpdate_" + fi.Name);
                        }

                        prop.SetStatements.Add(
                                new CodeExpressionStatement(
                                    new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(typeof(Sooda.ObjectMapper.SoodaObjectImpl)), "SetPlainFieldValue",

                                        // parameters
                                        new CodeThisReferenceExpression(),
                                        new CodePrimitiveExpression(fi.Table.OrdinalInClass),
                                        new CodePrimitiveExpression(fi.Name),
                                        new CodePrimitiveExpression(fi.ClassUnifiedOrdinal),
                                        Box(new CodePropertySetValueReferenceExpression()),
                                        beforeDelegate,
                                        afterDelegate
                                        )));
                    }
                }
            }


            if (classInfo.Collections1toN != null)
            {
                foreach (CollectionOnetoManyInfo coli in classInfo.Collections1toN)
                {
                    prop = new CodeMemberProperty();
                    prop.Name = coli.Name;
                    prop.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                    prop.Type = GetCollectionPropertyType(coli.ClassName);

                    prop.GetStatements.Add(
                        new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)), new CodeStatement[]
                            {
                                new CodeAssignStatement(
                                new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                                new CodeObjectCreateExpression(GetCollectionWrapperType(coli.ClassName),
                                new CodeObjectCreateExpression(new CodeTypeReference(typeof(Sooda.ObjectMapper.SoodaObjectOneToManyCollection)),
                                new CodeExpression[] {
                                    new CodeMethodInvokeExpression(This, "GetTransaction"),
                                    new CodeTypeOfExpression(new CodeTypeReference(coli.ClassName)),
                                    new CodeThisReferenceExpression(),
                                    new CodePrimitiveExpression(coli.ForeignFieldName),
                                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(coli.ClassName + "_Factory"), "TheClassInfo"),
                                    new CodeFieldReferenceExpression(null, "_collectionWhere_" + coli.Name),
                                    new CodePrimitiveExpression(coli.Cache)
                            }))),
                    }, new CodeStatement[] { }));

                    prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name)));
                    ctd.Members.Add(prop);

#if DOTNET35
                    CodeExpression whereExpression = new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(Sooda.QL.Soql)),
                        "FieldEquals",
                        new CodePrimitiveExpression(coli.ForeignFieldName),
                        This);
                    if (!string.IsNullOrEmpty(coli.Where))
                    {
                        whereExpression = new CodeObjectCreateExpression(
                            typeof(Sooda.QL.SoqlBooleanAndExpression),
                            whereExpression,
                            new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(null, "_collectionWhere_" + coli.Name), "WhereExpression"));
                    }
                    prop = GetCollectionLinqQuery(coli, whereExpression);
                    ctd.Members.Add(prop);
#endif
                }
            }

            if (classInfo.CollectionsNtoN != null)
            {
                foreach (CollectionManyToManyInfo coli in classInfo.CollectionsNtoN)
                {
                    RelationInfo relationInfo = coli.GetRelationInfo();
                    // FieldInfo masterField = relationInfo.Table.Fields[1 - coli.MasterField];

                    string relationTargetClass = relationInfo.Table.Fields[coli.MasterField].References;

                    prop = new CodeMemberProperty();
                    prop.Name = coli.Name;
                    prop.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                    prop.Type = GetCollectionPropertyType(relationTargetClass);

                    prop.GetStatements.Add(
                        new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null)), new CodeStatement[] {
                                                                                    new CodeAssignStatement(
                                                                                    new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name),
                                                                                    new CodeObjectCreateExpression(GetCollectionWrapperType(relationTargetClass),
                                                                                    new CodeObjectCreateExpression(new CodeTypeReference(typeof(Sooda.ObjectMapper.SoodaObjectManyToManyCollection)),
                                                                                    new CodeExpression[] {
                                                                                                             new CodeMethodInvokeExpression(This, "GetTransaction"),
                                                                                                             new CodePrimitiveExpression(coli.MasterField),
                                                                                                             new CodeMethodInvokeExpression(This, "GetPrimaryKeyValue"),
                                                                                                             new CodeTypeOfExpression(relationInfo.Name + "_RelationTable"),
                                                                                                             new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(relationInfo.Name + "_RelationTable"), "theRelationInfo")

                                                                                                         }))
                                                                                    ),
                    }
                        , new CodeStatement[] { }));

                    prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(This, "_collectionCache_" + coli.Name)));

                    ctd.Members.Add(prop);

#if DOTNET35
                    CodeExpression whereExpression = new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(Sooda.QL.Soql)),
                        "CollectionFor",
                        new CodeMethodInvokeExpression(
                                new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(classInfo.Name + "_Factory"), "TheClassInfo"),
                                "FindCollectionManyToMany",
                                new CodePrimitiveExpression(coli.Name)),
                        This);
                    prop = GetCollectionLinqQuery(coli, whereExpression);
                    ctd.Members.Add(prop);
#endif
                }
            }
        }
コード例 #18
0
 protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
 {
     base.Output.Write("AddressOf ");
     base.GenerateExpression(e.TargetObject);
     base.Output.Write(".");
     this.OutputIdentifier(e.MethodName);
 }
コード例 #19
0
ファイル: csharpcodeprovider.cs プロジェクト: ArildF/masters
 /// <include file='doc\CSharpCodeProvider.uex' path='docs/doc[@for="CSharpCodeGenerator.GenerateDelegateCreateExpression"]/*' />
 /// <devdoc>
 ///    <para>
 ///       Generates code for the specified CodeDom based delegate creation
 ///       expression representation.
 ///    </para>
 /// </devdoc>
 protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e) {
     Output.Write("new ");
     OutputType(e.DelegateType);
     Output.Write("(");
     GenerateExpression(e.TargetObject);
     Output.Write(".");
     OutputIdentifier(e.MethodName);
     Output.Write(")");
 }
コード例 #20
0
ファイル: CodeGeneratorCas.cs プロジェクト: Profit0004/mono
		protected override void GenerateDelegateCreateExpression (CodeDelegateCreateExpression e)
		{
		}
コード例 #21
0
ファイル: EmitExpr.cs プロジェクト: Tyelpion/IronAHK
        private Type EmitDelegateCreateExpression(CodeDelegateCreateExpression del)
        {
            Depth++;
            Debug("Emitting delegate: " + del.MethodName);

            // HACK: use generic method lookup for emitting delegates

            if (!Methods.ContainsKey(del.MethodName))
                throw new CompileException(del, "Delegate function does not exist in local scope");

            var method = (MethodInfo) Methods[del.MethodName].Method;
            Generator.Emit(OpCodes.Ldnull);
            Generator.Emit(OpCodes.Ldftn, method);

            var type = del.DelegateType.UserData[Parser.RawData] as Type ?? Type.GetType(del.DelegateType.BaseType);

            if (type == null)
                throw new CompileException(del, "Invalid delegate type");

            if (Mirror != null)
                type = Mirror.GrabType(type);

            var ctor = type.GetConstructors()[0];

            Generator.Emit(OpCodes.Newobj, ctor);

            Depth--;

            return type;
        }
コード例 #22
0
        private CodeExpression BuildExpression(XSharpParser.PrimaryExpressionContext expression)
        {
            CodeExpression expr = null;
            XSharpParser.PrimaryContext ctx = expression.Expr;
            //
            if (ctx is XSharpParser.SelfExpressionContext) // Self
            {
                expr = new CodeThisReferenceExpression();
            }
            else if (ctx is XSharpParser.SuperExpressionContext) // Super
            {
                expr = new CodeBaseReferenceExpression();
            }
            else if (ctx is XSharpParser.LiteralExpressionContext)
            {
                XSharpParser.LiteralExpressionContext lit = (XSharpParser.LiteralExpressionContext)ctx;
                expr = BuildLiteralValue(lit.Literal);
            }
            else if (ctx is XSharpParser.LiteralArrayExpressionContext) // { expr [, expr] }
            {
                XSharpParser.LiteralArrayContext arr = ((XSharpParser.LiteralArrayExpressionContext)ctx).LiteralArray;
                // Typed Array ?
                if (arr.Type != null)
                {
                    List<CodeExpression> exprlist = new List<CodeExpression>();
                    foreach (var Element in arr._Elements)
                    {
                        exprlist.Add(BuildExpression(Element.Expr,true));
                    }
                    expr = new CodeArrayCreateExpression(BuildDataType(arr.Type), exprlist.ToArray());
                }
                else
                {
                    expr = new CodeSnippetExpression(arr.GetText());
                }
            }
            else if (ctx is XSharpParser.DelegateCtorCallContext)
            {
                XSharpParser.DelegateCtorCallContext delg = (XSharpParser.DelegateCtorCallContext)ctx;
                //
                CodeTypeReference ctr = BuildDataType(delg.Type);
                CodeExpression ce = BuildExpression(delg.Obj,false);
                //
                expr = new CodeDelegateCreateExpression(BuildDataType(delg.Type), BuildExpression(delg.Obj,false), delg.Func.GetText());

            }
            else if (ctx is XSharpParser.CtorCallContext)
            {
                XSharpParser.CtorCallContext ctor = (XSharpParser.CtorCallContext)ctx;
                CodeTypeReference ctr = BuildDataType(ctor.Type);
                List<CodeExpression> exprlist = new List<CodeExpression>();
                if (ctor.ArgList != null)
                {
                    foreach (var arg in ctor.ArgList._Args)
                    {
                        // We should handle arg.Name if arg.ASSIGN_OP is not null...
                        exprlist.Add(BuildExpression(arg.Expr,false));
                    }
                }
                expr = new CodeObjectCreateExpression(ctr.BaseType, exprlist.ToArray());
            }
            else if (ctx is XSharpParser.TypeOfExpressionContext)
            {
                CodeTypeReference ctr = BuildDataType(((XSharpParser.TypeOfExpressionContext)ctx).Type);
                expr = new CodeTypeOfExpression(ctr);
            }
            else if (ctx is XSharpParser.NameExpressionContext)
            {
                String name = ((XSharpParser.NameExpressionContext)ctx).Name.Id.GetText();
                // Sometimes, we will need to do it that way....
                if (name.ToLower() == "self")
                {
                    expr = new CodeThisReferenceExpression();
                }
                else if (name.ToLower() == "super")
                {
                    expr = new CodeBaseReferenceExpression();
                }
                else
                {
                    CodeTypeReference ctr = BuildSimpleName(((XSharpParser.NameExpressionContext)ctx).Name);
                    expr = new CodeVariableReferenceExpression(name);
                }
            }
            else
            {
                expr = new CodeSnippetExpression(ctx.GetText());
            }
            return expr;
        }
コード例 #23
0
 protected override void GenerateDelegateCreateExpression(System.CodeDom.CodeDelegateCreateExpression e)
 {
     Output.Write(e.MethodName);
 }
コード例 #24
0
        private CodeExpression GetEventDelegate(CodeContext cc, MemberInfo miEvent, string eventName, string eventHandler)
        {
            Type eventTarget = cc != null ? cc.ElementType : miEvent.DeclaringType;
            string eventTargetName = eventTarget != null ? eventTarget.FullName : cc.LocalElementFullName;

            bool subClassed = _ccRoot.SubClass.Length > 0;
            CodeDelegateCreateExpression cdce = new CodeDelegateCreateExpression();

            // Fetch the EventHandlerType from either the EventInfo or the MethodInfo
            // for the Add{Propertyname}Handler method's MethodInfo
            Type eventHandlerType = GetEventHandlerType(miEvent);
            string [] typeArgsList = cc != null ? cc.GenericTypeArgs : null;

            cdce.DelegateType = GenerateConstructedTypeReference(eventHandlerType, typeArgsList, eventTarget, eventTargetName, eventName);
            cdce.MethodName = eventHandler.Trim() + (subClassed ? HELPER : string.Empty);
            cdce.TargetObject = new CodeThisReferenceExpression();
            CodeExpression cDelExp = cdce;

            // NOTE: workaround for VB CodeDom bug which does not produce correct Delegate expression code
            if (IsLanguageVB)
            {
                CodeExpression[] delParams = { cdce };
                CodeObjectCreateExpression coce = new CodeObjectCreateExpression(eventHandlerType, delParams);
                cDelExp = coce;
            }

//            The bug that this chunk of code works around (VS#542946) was fixed but
//            exposes a different bug (VS#572060)   To work around the second bug, we
//            remove the workaround for the first one.  (RogerCh 20020918)

//            Note that #542946 was not fixed for VB, so the code block above remains.

//            else if (Language == CompilerLanguage.JScript)
//            {
//                CodeCastExpression cce = new CodeCastExpression(mei.ei.EventHandlerType, cdce);
//                cDelExp = cce;
//            }

            return cDelExp;
        }
コード例 #25
0
		void AddEventAssign (CodeMemberMethod method, ControlBuilder builder, string name, Type type, string value)
		{
			//"__ctrl.{0} += new {1} (this.{2});"
			CodeEventReferenceExpression evtID = new CodeEventReferenceExpression (ctrlVar, name);

			CodeDelegateCreateExpression create;
			create = new CodeDelegateCreateExpression (new CodeTypeReference (type), thisRef, value);

			CodeAttachEventStatement attach = new CodeAttachEventStatement (evtID, create);
			method.Statements.Add (attach);
		}
コード例 #26
0
		protected override void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e)
		{
			Output.Write("[CodeDelegateCreateExpression: {0}]", e.ToString());
		}
コード例 #27
0
		void AddBindableTemplateInvocation (ControlBuilder builder, string name, string methodName, string extractMethodName)
		{
			CodePropertyReferenceExpression prop = new CodePropertyReferenceExpression (ctrlVar, name);

			CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);

			CodeDelegateCreateExpression newExtract = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (ExtractTemplateValuesMethod)), thisRef, extractMethodName);

			CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledBindableTemplateBuilder));
			newCompiled.Parameters.Add (newBuild);
			newCompiled.Parameters.Add (newExtract);
			
			CodeAssignStatement assign = new CodeAssignStatement (prop, newCompiled);
			builder.Method.Statements.Add (AddLinePragma (assign, builder));
		}
コード例 #28
0
        public override bool AddEventHandler(EventDescription eventDescription, string objectName, string methodName)
        {
            const string Init = "__init__";
            //This is not the most optimal solution for WPF since we will call FindLogicalNode for each event handler,
            //but it simplifies the code generation for now.

            CodeDomDocDataAdapter adapter = GetDocDataAdapterForPyFile();

            //Find the __init__ method
            CodeMemberMethod method = null;
            foreach(CodeTypeMember ctMember in adapter.TypeDeclaration.Members)
            {
                if (ctMember is CodeConstructor)
                {
                    if (ctMember.Name == Init)
                    {
                        method = ctMember as CodeMemberMethod;
                        break;
                    }
                }
            }
            if (method == null)
            {
                method = new CodeConstructor();
                method.Name = Init;
            }

            //Create a code statement which looks like: LogicalTreeHelper.FindLogicalNode(self.Root, "button1").Click += self.button1_Click
            CodeTypeReferenceExpression logicalTreeHelper = new CodeTypeReferenceExpression("LogicalTreeHelper");
            CodeMethodReferenceExpression findLogicalNodeMethod = new CodeMethodReferenceExpression(logicalTreeHelper, "FindLogicalNode");
            CodeFieldReferenceExpression selfWindow = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Root");
            CodeMethodInvokeExpression findLogicalNodeInvoke = new CodeMethodInvokeExpression( findLogicalNodeMethod, selfWindow, new CodeSnippetExpression("\'" + objectName + "\'"));
            CodeDelegateCreateExpression createDelegateExpression = new CodeDelegateCreateExpression(new CodeTypeReference("System.EventHandler"), new CodeThisReferenceExpression(), methodName);
            CodeAttachEventStatement attachEvent = new CodeAttachEventStatement(findLogicalNodeInvoke, eventDescription.Name, createDelegateExpression);
            method.Statements.Add(attachEvent);
            adapter.Generate();
            return true;
        }
コード例 #29
0
		void AddContentTemplateInvocation (ContentBuilderInternal cbuilder, CodeMemberMethod method, string methodName)
		{
			CodeDelegateCreateExpression newBuild = new CodeDelegateCreateExpression (
				new CodeTypeReference (typeof (BuildTemplateMethod)), thisRef, methodName);

			CodeObjectCreateExpression newCompiled = new CodeObjectCreateExpression (typeof (CompiledTemplateBuilder));
			newCompiled.Parameters.Add (newBuild);
			
			CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression (thisRef, "AddContentTemplate");
			invoke.Parameters.Add (new CodePrimitiveExpression (cbuilder.ContentPlaceHolderID));
			invoke.Parameters.Add (newCompiled);

			method.Statements.Add (AddLinePragma (invoke, cbuilder));
		}
 private void GenerateCodeFromDelegateCreateExpression(CodeDelegateCreateExpression e, TextWriter w)
 {
     w.Write("$" + e.MethodName);
 }
コード例 #31
0
		protected void CreateControlTree (ControlBuilder builder, bool inTemplate, bool childrenAsProperties)
		{
			EnsureID (builder);
			bool isTemplate = builder.IsTemplate;
			
			if (!isTemplate && !inTemplate) {
				CreateField (builder, true);
			} else if (!isTemplate) {
				bool doCheck = false;				
				bool singleInstance = false;
				ControlBuilder pb = builder.ParentBuilder;
				TemplateBuilder tpb;
				while (pb != null) {
					tpb = pb as TemplateBuilder;
					if (tpb == null) {
						pb = pb.ParentBuilder;
						continue;
					}
					
					if (tpb.TemplateInstance == TemplateInstance.Single)
						singleInstance = true;
					break;
				}
				
				if (!singleInstance)
					builder.ID = builder.GetNextID (null);
				else
					doCheck = true;

				CreateField (builder, doCheck);
			}

			InitMethod (builder, isTemplate, childrenAsProperties);
			if (!isTemplate || builder.GetType () == typeof (RootBuilder))
				CreateAssignStatementsFromAttributes (builder);

			if (builder.Children != null && builder.Children.Count > 0) {
				StringBuilder sb = new StringBuilder ();
				foreach (object b in builder.Children) {
					if (b is string) {
						sb.Append ((string) b);
						continue;
					}

					FlushText (builder, sb);
					if (b is ObjectTagBuilder) {
						ProcessObjectTag ((ObjectTagBuilder) b);
					} else if (b is StringPropertyBuilder) {
						StringPropertyBuilder pb = b as StringPropertyBuilder;
						if (pb.Children != null && pb.Children.Count > 0) {
							StringBuilder asb = new StringBuilder ();
							foreach (string s in pb.Children)
								asb.Append (s);
							CodeMemberMethod method = builder.Method;
							CodeAssignStatement assign = new CodeAssignStatement ();
							assign.Left = new CodePropertyReferenceExpression (ctrlVar, pb.PropertyName);
							assign.Right = new CodePrimitiveExpression (asb.ToString ());
							method.Statements.Add (AddLinePragma (assign, builder));
						}
					} else if (b is ContentBuilderInternal) {
						ContentBuilderInternal cb = (ContentBuilderInternal) b;
						CreateControlTree (cb, false, true);
						AddContentTemplateInvocation (cb, builder.Method, cb.Method.Name);
						continue;
					}

					// Ignore TemplateBuilders - they are processed in InitMethod
					else if (b is TemplateBuilder) {
					} else if (b is CodeRenderBuilder) {
						AddCodeRender (builder, (CodeRenderBuilder) b);
					} else if (b is DataBindingBuilder) {
						AddDataBindingLiteral (builder, (DataBindingBuilder) b);
					} else if (b is ControlBuilder) {
						ControlBuilder child = (ControlBuilder) b;
						CreateControlTree (child, inTemplate, builder.ChildrenAsProperties);
						AddChildCall (builder, child);
						continue;
					} else
						throw new Exception ("???");

					ControlBuilder bldr = b as ControlBuilder;
					bldr.ProcessGeneratedCode (CompileUnit, BaseType, DerivedType, bldr.Method, bldr.DataBindingMethod);
				}

				FlushText (builder, sb);
			}

			ControlBuilder defaultPropertyBuilder = builder.DefaultPropertyBuilder;
			if (defaultPropertyBuilder != null) {
				CreateControlTree (defaultPropertyBuilder, false, true);
				AddChildCall (builder, defaultPropertyBuilder);
			}
			
			if (builder.HasAspCode) {
				CodeMemberMethod renderMethod = builder.RenderMethod;
				CodeMethodReferenceExpression m = new CodeMethodReferenceExpression ();
				m.TargetObject = thisRef;
				m.MethodName = renderMethod.Name;

				CodeDelegateCreateExpression create = new CodeDelegateCreateExpression ();
				create.DelegateType = new CodeTypeReference (typeof (RenderMethod));
				create.TargetObject = thisRef;
				create.MethodName = renderMethod.Name;

				CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ();
				invoke.Method = new CodeMethodReferenceExpression (ctrlVar, "SetRenderMethodDelegate");
				invoke.Parameters.Add (create);

				builder.MethodStatements.Add (invoke);
			}

			if (builder is RootBuilder)
				if (!String.IsNullOrEmpty (parser.MetaResourceKey))
					AssignPropertiesFromResources (builder, parser.BaseType, parser.MetaResourceKey);
			
			if ((!isTemplate || builder is RootBuilder) && !String.IsNullOrEmpty (builder.GetAttribute ("meta:resourcekey")))
				CreateAssignStatementFromAttribute (builder, "meta:resourcekey");
			
			if ((childrenAsProperties && builder.PropertyBuilderShouldReturnValue) || (!childrenAsProperties && typeof (Control).IsAssignableFrom (builder.ControlType)))
				builder.Method.Statements.Add (new CodeMethodReturnStatement (ctrlVar));

			builder.ProcessGeneratedCode (CompileUnit, BaseType, DerivedType, builder.Method, builder.DataBindingMethod);
		}