protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e) { Output.Write("[CodeEventReferenceExpression: Name={0}, Target=", e.EventName); this.GenerateExpression(e.TargetObject); Output.Write("]"); }
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); }
protected override void GenerateEventReferenceExpression (CodeEventReferenceExpression e) { if(e.TargetObject != null) { GenerateExpression(e.TargetObject); Output.Write("."); } OutputIdentifier(e.EventName); }
static void _Patch(CodeFieldReferenceExpression fr, CodeDomVisitContext ctx, CodeDomResolver resolver) { if (null != fr) { var path = _GetUnresRootPathOfExpression(fr); if (null != path) { // now we have something to work with. var scope = resolver.GetScope(fr); var sa = path.Split('.'); if (1 == sa.Length) { System.Diagnostics.Debugger.Break(); throw new NotImplementedException(); } else { object t = null; string tn = null; CodeExpression tf = fr; CodeExpression ptf = null; CodeTypeReference ctr = null; for (var i = sa.Length - 1; i >= 1; --i) { tn = string.Join(".", sa, 0, i); ptf = tf; tf = _GetTargetOfExpression(tf); ctr = new CodeTypeReference(tn); t = resolver.TryResolveType(ctr, scope); if (null != t) { break; } } if (null != t) { var tt = t as Type; if (null != tt) { ctr = new CodeTypeReference(tt); } else { ctr = resolver.GetQualifiedType(ctr, scope); } // we found a type reference _SetTargetOfExpression(ptf, new CodeTypeReferenceExpression(ctr)); return; //args.Cancel = true; } } } // this probably means part of our field has been resolved, or at the very least // it does not come from a rooted var ref. if (!fr.TargetObject.UserData.Contains("slang:unresolved")) { var scope = resolver.GetScope(fr); var binder = new CodeDomBinder(scope); var t = resolver.GetTypeOfExpression(fr.TargetObject); var isStatic = false; var tre = fr.TargetObject as CodeTypeReferenceExpression; if (null != tre) { isStatic = true; } var tt = resolver.TryResolveType(isStatic ? tre.Type: t, scope); if (null == tt) { throw new InvalidOperationException(string.Format("The type {0} could not be resolved.", t.BaseType)); } var td = tt as CodeTypeDeclaration; // TODO: This code could be a lot faster if we added some functionality to the binder // we're just checking to see if the method, property or field exists var m = binder.GetField(tt, fr.FieldName, _BindFlags); if (null != m) { fr.UserData.Remove("slang:unresolved"); return; } m = binder.GetEvent(tt, fr.FieldName, _BindFlags); if (null != m) { var er = new CodeEventReferenceExpression(fr.TargetObject, fr.FieldName); CodeDomVisitor.ReplaceTarget(ctx, er); return; } var ml = binder.GetMethodGroup(tt, fr.FieldName, _BindFlags); if (0 < ml.Length) { var mr = new CodeMethodReferenceExpression(fr.TargetObject, fr.FieldName); CodeDomVisitor.ReplaceTarget(ctx, mr); return; } ml = binder.GetPropertyGroup(tt, fr.FieldName, _BindFlags); if (0 < ml.Length) { var pr = new CodePropertyReferenceExpression(fr.TargetObject, fr.FieldName); CodeDomVisitor.ReplaceTarget(ctx, pr); return; } throw new InvalidProgramException(string.Format("Cannot deterimine the target reference {0}", fr.FieldName)); } } }
public CodeRemoveEventStatement(CodeEventReferenceExpression eventRef, CodeExpression listener) { _eventRef = eventRef; Listener = listener; }
private static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent) { CodeObjectCreateExpression expression; CodeMemberMethod method = new CodeMemberMethod(); method.Attributes = MemberAttributes.Private; method.Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations); method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state")); method.ReturnType = new CodeTypeReference(voidType); CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e"); statement.InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName, new CodeArgumentReferenceExpression(method.Parameters[0].Name)); CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(statement.Name); if (operationCompletedEventArgsType != null) { expression = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[0]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } else { expression = new CodeObjectCreateExpression(asyncCompletedEventArgsType, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) }); } CodeEventReferenceExpression expression3 = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name); CodeDelegateInvokeExpression expression4 = new CodeDelegateInvokeExpression(expression3, new CodeExpression[] { new CodeThisReferenceExpression(), expression }); CodeConditionStatement statement2 = new CodeConditionStatement(new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeStatement[] { statement, new CodeExpressionStatement(expression4) }); method.Statements.Add(statement2); clientType.Members.Add(method); return method; }
public CodeRemoveEventStatement(CodeExpression targetObject, string eventName, CodeExpression listener) { _eventRef = new CodeEventReferenceExpression(targetObject, eventName); Listener = listener; }
public void Visit(CodeEventReferenceExpression o) { g.GenerateEventReferenceExpression(o); }
private void ValidateEventReferenceExpression(CodeEventReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.EventName), e.EventName); }
public override void Transform(ITypedElement feature, CodeTypeDeclaration generatedType, ITransformationContext context) { generatedType.Name = feature.Name.ToPascalCase() + "Proxy"; generatedType.Attributes = MemberAttributes.Private | MemberAttributes.Final; generatedType.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed; generatedType.WriteDocumentation(string.Format("Represents a proxy to represent an incremental access to the {0} property", feature.Name)); var type = CreateReference(feature.Type, feature is IReference, context); var t = Transformation as Meta2ClassesTransformation; if ((t == null || t.IsValueType(feature.Type)) && feature.LowerBound == 0 && feature.UpperBound == 1) { type = new CodeTypeReference(typeof(System.Nullable <>).Name, type); } var declaringType = context.Trace.ResolveIn(Rule <Type2Type>(), feature.Parent as IType).GetReferenceForType(); generatedType.BaseTypes.Add(new CodeTypeReference("ModelPropertyChange", declaringType, type)); var modelElementRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ModelElement"); var property = context.Trace.ResolveIn(Rule <Feature2Property>(), feature); var propertyRef = new CodePropertyReferenceExpression(modelElementRef, property.Name); var propertyChanged = new CodeEventReferenceExpression(modelElementRef, property.Name + "Changed"); var value = new CodeMemberProperty() { Name = "Value", Attributes = MemberAttributes.Public | MemberAttributes.Override, Type = type }; value.WriteDocumentation("Gets or sets the value of this expression"); value.GetStatements.Add(new CodeMethodReturnStatement(propertyRef)); value.SetStatements.Add(new CodeAssignStatement(propertyRef, new CodePropertySetValueReferenceExpression())); generatedType.Members.Add(value); var handlerParameter = new CodeParameterDeclarationExpression(typeof(EventHandler <ValueChangedEventArgs>), "handler"); var handlerParameterRef = new CodeArgumentReferenceExpression("handler"); var registerChangeEventHandler = new CodeMemberMethod() { Name = "RegisterChangeEventHandler", Attributes = MemberAttributes.Family | MemberAttributes.Override, ReturnType = null }; registerChangeEventHandler.WriteDocumentation("Registers an event handler to subscribe specifically on the changed event for this property", null, new Dictionary <string, string>() { { "handler", "The handler that should be subscribed to the property change event" } }); registerChangeEventHandler.Parameters.Add(handlerParameter); registerChangeEventHandler.Statements.Add(new CodeAttachEventStatement(propertyChanged, handlerParameterRef)); generatedType.Members.Add(registerChangeEventHandler); var unregisterChangeEventHandler = new CodeMemberMethod() { Name = "UnregisterChangeEventHandler", Attributes = MemberAttributes.Family | MemberAttributes.Override, ReturnType = null }; unregisterChangeEventHandler.WriteDocumentation("Registers an event handler to subscribe specifically on the changed event for this property", null, new Dictionary <string, string>() { { "handler", "The handler that should be unsubscribed from the property change event" } }); unregisterChangeEventHandler.Parameters.Add(handlerParameter); unregisterChangeEventHandler.Statements.Add(new CodeRemoveEventStatement(propertyChanged, handlerParameterRef)); generatedType.Members.Add(unregisterChangeEventHandler); var constructor = new CodeConstructor() { Attributes = MemberAttributes.Public }; constructor.WriteDocumentation("Creates a new observable property access proxy", null, new Dictionary <string, string>() { { "modelElement", "The model instance element for which to create the property access proxy" } }); constructor.Parameters.Add(new CodeParameterDeclarationExpression(declaringType, "modelElement")); constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("modelElement")); generatedType.Members.Add(constructor); }
void AddAsyncMembers(string messageName, CodeMemberMethod method) { CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodePrimitiveExpression enull = new CodePrimitiveExpression(null); CodeMemberField codeField = new CodeMemberField(typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted"); codeField.Attributes = MemberAttributes.Private; CodeTypeDeclaration.Members.Add(codeField); // Event arguments class string argsClassName = classNames.AddUnique(messageName + "CompletedEventArgs", null); CodeTypeDeclaration argsClass = new CodeTypeDeclaration(argsClassName); argsClass.Attributes |= MemberAttributes.Public; #if NET_2_0 argsClass.IsPartial = true; #endif argsClass.BaseTypes.Add(new CodeTypeReference("System.ComponentModel.AsyncCompletedEventArgs")); CodeMemberField resultsField = new CodeMemberField(typeof(object[]), "results"); resultsField.Attributes = MemberAttributes.Private; argsClass.Members.Add(resultsField); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Assembly; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "results")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Exception), "exception")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("exception")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("cancelled")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("userState")); CodeExpression thisResults = new CodeFieldReferenceExpression(ethis, "results"); cc.Statements.Add(new CodeAssignStatement(thisResults, new CodeVariableReferenceExpression("results"))); argsClass.Members.Add(cc); int ind = 0; if (method.ReturnType.BaseType != "System.Void") { argsClass.Members.Add(CreateArgsProperty(method.ReturnType, "Result", ind++)); } foreach (CodeParameterDeclarationExpression par in method.Parameters) { if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref) { argsClass.Members.Add(CreateArgsProperty(par.Type, par.Name, ind++)); } } bool needsArgsClass = (ind > 0); if (needsArgsClass) { asyncTypes.Add(argsClass); } else { argsClassName = "System.ComponentModel.AsyncCompletedEventArgs"; } // Event delegate type CodeTypeDelegate delegateType = new CodeTypeDelegate(messageName + "CompletedEventHandler"); delegateType.Attributes |= MemberAttributes.Public; delegateType.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); delegateType.Parameters.Add(new CodeParameterDeclarationExpression(argsClassName, "args")); // Event member CodeMemberEvent codeEvent = new CodeMemberEvent(); codeEvent.Attributes = codeEvent.Attributes & ~MemberAttributes.AccessMask | MemberAttributes.Public; codeEvent.Name = messageName + "Completed"; codeEvent.Type = new CodeTypeReference(delegateType.Name); CodeTypeDeclaration.Members.Add(codeEvent); // Async method (without user state param) CodeMemberMethod am = new CodeMemberMethod(); am.Attributes = MemberAttributes.Public | MemberAttributes.Final; am.Name = method.Name + "Async"; am.ReturnType = new CodeTypeReference(typeof(void)); CodeMethodInvokeExpression inv; inv = new CodeMethodInvokeExpression(ethis, am.Name); am.Statements.Add(inv); // On...Completed method CodeMemberMethod onCompleted = new CodeMemberMethod(); onCompleted.Name = "On" + messageName + "Completed"; onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final; onCompleted.ReturnType = new CodeTypeReference(typeof(void)); onCompleted.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "arg")); CodeConditionStatement anIf = new CodeConditionStatement(); CodeExpression eventField = new CodeEventReferenceExpression(ethis, codeEvent.Name); anIf.Condition = new CodeBinaryOperatorExpression(eventField, CodeBinaryOperatorType.IdentityInequality, enull); CodeExpression castedArg = new CodeCastExpression(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression("arg")); CodeStatement invokeArgs = new CodeVariableDeclarationStatement(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg); anIf.TrueStatements.Add(invokeArgs); CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression(); delegateInvoke.TargetObject = eventField; delegateInvoke.Parameters.Add(ethis); CodeObjectCreateExpression argsInstance = new CodeObjectCreateExpression(argsClassName); CodeExpression invokeArgsVar = new CodeVariableReferenceExpression("invokeArgs"); if (needsArgsClass) { argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Results")); } argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Error")); argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Cancelled")); argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "UserState")); delegateInvoke.Parameters.Add(argsInstance); anIf.TrueStatements.Add(delegateInvoke); onCompleted.Statements.Add(anIf); // Async method CodeMemberMethod asyncMethod = new CodeMemberMethod(); asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; asyncMethod.Name = method.Name + "Async"; asyncMethod.ReturnType = new CodeTypeReference(typeof(void)); CodeExpression delegateField = new CodeFieldReferenceExpression(ethis, codeField.Name); anIf = new CodeConditionStatement(); anIf.Condition = new CodeBinaryOperatorExpression(delegateField, CodeBinaryOperatorType.IdentityEquality, enull);; CodeExpression delegateRef = new CodeMethodReferenceExpression(ethis, onCompleted.Name); CodeExpression newDelegate = new CodeObjectCreateExpression(typeof(System.Threading.SendOrPostCallback), delegateRef); CodeAssignStatement cas = new CodeAssignStatement(delegateField, newDelegate); anIf.TrueStatements.Add(cas); asyncMethod.Statements.Add(anIf); CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression(typeof(object)); // Assign parameters CodeIdentifiers paramsIds = new CodeIdentifiers(); foreach (CodeParameterDeclarationExpression par in method.Parameters) { paramsIds.Add(par.Name, null); if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref) { CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression(par.Type, par.Name); am.Parameters.Add(inpar); asyncMethod.Parameters.Add(inpar); inv.Parameters.Add(new CodeVariableReferenceExpression(par.Name)); paramsArray.Initializers.Add(new CodeVariableReferenceExpression(par.Name)); } } inv.Parameters.Add(enull); string userStateName = paramsIds.AddUnique("userState", null); asyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userStateName)); CodeExpression userStateVar = new CodeVariableReferenceExpression(userStateName); asyncMethod.Statements.Add(BuildInvokeAsync(messageName, paramsArray, delegateField, userStateVar)); CodeTypeDeclaration.Members.Add(am); CodeTypeDeclaration.Members.Add(asyncMethod); CodeTypeDeclaration.Members.Add(onCompleted); asyncTypes.Add(delegateType); }
/// <summary> /// This method actually performs the serialization. When the member is serialized /// the necessary statements will be added to the statements collection. /// </summary> public override void Serialize(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements) { if (manager == null) { throw new ArgumentNullException(nameof(manager)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (!(descriptor is EventDescriptor eventToSerialize)) { throw new ArgumentNullException(nameof(descriptor)); } if (statements == null) { throw new ArgumentNullException(nameof(statements)); } try { IEventBindingService eventBindings = (IEventBindingService)manager.GetService(typeof(IEventBindingService)); // If the IEventBindingService is not available, we don't throw - we just don't do anything. if (eventBindings != null) { PropertyDescriptor prop = eventBindings.GetEventProperty(eventToSerialize); string methodName = (string)prop.GetValue(value); if (methodName != null) { CodeDomSerializer.Trace("Event {0} bound to {1}", eventToSerialize.Name, methodName); CodeExpression eventTarget = SerializeToExpression(manager, value); CodeDomSerializer.TraceWarningIf(eventTarget == null, "Object has no name and no propery ref in context so we cannot serialize events: {0}", value); if (eventTarget != null) { CodeTypeReference delegateTypeRef = new CodeTypeReference(eventToSerialize.EventType); CodeDelegateCreateExpression delegateCreate = new CodeDelegateCreateExpression(delegateTypeRef, _thisRef, methodName); CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(eventTarget, eventToSerialize.Name); CodeAttachEventStatement attach = new CodeAttachEventStatement(eventRef, delegateCreate); attach.UserData[typeof(Delegate)] = eventToSerialize.EventType; statements.Add(attach); } } } } catch (Exception e) { // Since we usually go through reflection, don't // show what our engine does, show what caused // the problem. // if (e is TargetInvocationException) { e = e.InnerException; } manager.ReportError(new CodeDomSerializerException(string.Format(SR.SerializerPropertyGenFailed, eventToSerialize.Name, e.Message), manager)); } }
public static string GenerateWrapper(WrapperClass wrapperClass, Language language) { // Namespace CodeNamespace _namespace = new CodeNamespace(wrapperClass.Namespace); // Comments string comment = @"------------------------------------------------------------------------------" + Environment.NewLine + @" <auto-generated>" + Environment.NewLine + @" This code was generated by '.NET Wrapper Class Generator'" + Environment.NewLine + @" Product Version:" + Assembly.GetExecutingAssembly().GetName().Version + Environment.NewLine + Environment.NewLine + @" Changes to this file may cause incorrect behavior and will be lost if" + Environment.NewLine + @" the code is regenerated." + Environment.NewLine + @" </auto-generated>" + Environment.NewLine + @" ------------------------------------------------------------------------------"; _namespace.Comments.Add(new CodeCommentStatement(comment)); // Class CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(wrapperClass.ClassName); classDeclaration.IsPartial = wrapperClass.Partial; if (wrapperClass.Sealed) { classDeclaration.TypeAttributes |= TypeAttributes.Sealed; } _namespace.Types.Add(classDeclaration); // Initialization CodeParameterDeclarationExpressionCollection initializationParameters = null; CodeStatementCollection initiazationStatements = null; if (wrapperClass.Partial) { // Initialization method CodeMemberMethod initializer = new CodeMemberMethod(); classDeclaration.Members.Add(initializer); initializer.Name = "InitializeWrapper"; initializer.Attributes = MemberAttributes.Private; { comment = @"***************************************************************" + Environment.NewLine + @" This method should be called by the user-provided constructor!" + Environment.NewLine + @"***************************************************************"; initializer.Comments.Add(new CodeCommentStatement(comment)); } initializationParameters = initializer.Parameters; initiazationStatements = initializer.Statements; } else { // Constructor CodeConstructor constructor = new CodeConstructor(); classDeclaration.Members.Add(constructor); constructor.Attributes = MemberAttributes.Public; initializationParameters = constructor.Parameters; initiazationStatements = constructor.Statements; } // Iterate over the wrapped types foreach (WrappedType wrappedType in wrapperClass.WrappedTypes) { // Fields CodeMemberField field = new CodeMemberField(wrappedType.Type, wrappedType.FieldName); if (wrappedType.Acquisition != Acquisition.UserManaged) { classDeclaration.Members.Add(field); } string memberPrefix = string.Empty; if (wrappedType.PrefixMembers) { memberPrefix = wrappedType.FieldName; memberPrefix = memberPrefix.Substring(0, 1).ToUpper() + memberPrefix.Substring(1); } CodeFieldReferenceExpression fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), wrappedType.FieldName); if (wrappedType.Acquisition == Acquisition.Construct) { // Instantiation CodeObjectCreateExpression instantiation = new CodeObjectCreateExpression(wrappedType.Type); CodeAssignStatement instanceAssignment = new CodeAssignStatement(fieldReference, instantiation); initiazationStatements.Add(instanceAssignment); } else if (wrappedType.Acquisition == Acquisition.Parameter) { // Pass as parameter initializationParameters.Add(new CodeParameterDeclarationExpression(wrappedType.Type, wrappedType.FieldName)); initiazationStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression(wrappedType.FieldName))); } else if (wrappedType.Acquisition == Acquisition.Property) { // Set as property CodeMemberProperty property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public; property.HasGet = property.HasSet = true; property.Type = new CodeTypeReference(wrappedType.Type); property.Name = wrappedType.Type.Name; property.GetStatements.Add(new CodeMethodReturnStatement(fieldReference)); property.SetStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression("value"))); classDeclaration.Members.Add(property); } // Methods foreach (WrappedMethod wrappedMethod in wrappedType.WrappedMethods) { // Method CodeMemberMethod method = new CodeMemberMethod(); classDeclaration.Members.Add(method); method.Name = memberPrefix + wrappedMethod.Method.Name; method.ReturnType = new CodeTypeReference(wrappedMethod.Method.ReturnType); Generator.SetMember(method, wrappedMethod); if (!string.IsNullOrEmpty(wrappedMethod.Interface)) { method.PrivateImplementationType = new CodeTypeReference(wrappedMethod.Interface); } // Parameters List <CodeExpression> arguments = Generator.SetParameters(method, wrappedMethod.Method.GetParameters()); // Statement CodeMethodInvokeExpression invocation = null; if (!wrappedMethod.Method.IsStatic) { invocation = new CodeMethodInvokeExpression(fieldReference, wrappedMethod.Method.Name, arguments.ToArray()); } else { invocation = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(wrappedType.Type), wrappedMethod.Method.Name, arguments.ToArray()); method.Attributes |= MemberAttributes.Static; } if (wrappedMethod.Method.ReturnType == typeof(void)) { method.Statements.Add(invocation); } else { method.Statements.Add(new CodeMethodReturnStatement(invocation)); } } // Properties foreach (WrappedProperty wrappedProperty in wrappedType.WrappedProperties) { // Property CodeMemberProperty property = new CodeMemberProperty(); classDeclaration.Members.Add(property); property.Name = memberPrefix + wrappedProperty.Property.Name; property.Type = new CodeTypeReference(wrappedProperty.Property.PropertyType); Generator.SetMember(property, wrappedProperty); if (!string.IsNullOrEmpty(wrappedProperty.Interface)) { property.PrivateImplementationType = new CodeTypeReference(wrappedProperty.Interface); } CodePropertyReferenceExpression invocation = null; if (true) // TODO: check if property is static { invocation = new CodePropertyReferenceExpression(fieldReference, wrappedProperty.Property.Name); } else { } // Get statement if (wrappedProperty.Get) { property.GetStatements.Add(new CodeMethodReturnStatement(invocation)); } // Set statement if (wrappedProperty.Set) { property.SetStatements.Add(new CodeAssignStatement(invocation, new CodeVariableReferenceExpression("value"))); } } // Events foreach (WrappedEvent wrappedEvent in wrappedType.WrappedEvents) { // Event MethodInfo eventDelegate = wrappedEvent.Event.EventHandlerType.GetMethod("Invoke"); CodeMemberEvent _event = new CodeMemberEvent(); classDeclaration.Members.Add(_event); _event.Name = memberPrefix + wrappedEvent.Event.Name; _event.Type = new CodeTypeReference(wrappedEvent.Event.EventHandlerType); Generator.SetMember(_event, wrappedEvent); if (!string.IsNullOrEmpty(wrappedEvent.Interface)) { _event.PrivateImplementationType = new CodeTypeReference(wrappedEvent.Interface); } // Event handler/raiser CodeMemberMethod eventHandler = new CodeMemberMethod(); classDeclaration.Members.Add(eventHandler); eventHandler.Name = string.Format("On{0}", _event.Name); eventHandler.ReturnType = new CodeTypeReference(eventDelegate.ReturnType); eventHandler.Attributes = MemberAttributes.Private; List <CodeExpression> arguments = Generator.SetParameters(eventHandler, eventDelegate.GetParameters()); CodeEventReferenceExpression eventReference = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _event.Name); CodeConditionStatement conditional = new CodeConditionStatement(); eventHandler.Statements.Add(conditional); conditional.Condition = new CodeBinaryOperatorExpression(eventReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); CodeDelegateInvokeExpression eventInvocation = new CodeDelegateInvokeExpression(eventReference, arguments.ToArray()); if (eventDelegate.ReturnType == typeof(void)) { conditional.TrueStatements.Add(eventInvocation); } else { conditional.TrueStatements.Add(new CodeMethodReturnStatement(eventInvocation)); } // Event registration CodeEventReferenceExpression wrappedEventReference = new CodeEventReferenceExpression(fieldReference, wrappedEvent.Event.Name); CodeMethodReferenceExpression eventRaiserReference = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), eventHandler.Name); CodeAttachEventStatement eventRegistration = new CodeAttachEventStatement(wrappedEventReference, eventRaiserReference); initiazationStatements.Add(eventRegistration); } } // Generate the code StringWriter stringWriter = new StringWriter(); CodeDomProvider codeProvider = null; if (language == Language.CSharp) { codeProvider = new CSharpCodeProvider(); } else if (language == Language.VBNet) { codeProvider = new VBCodeProvider(); } else { throw new ArgumentException("Specified language is not supported: " + language); } CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; codeProvider.GenerateCodeFromNamespace(_namespace, stringWriter, options); return(stringWriter.ToString()); }
protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e) { Output.Write("eventReference"); }
private void GenerateCallJ2C(CodeMemberMethod tgtMethod, GMethod method) { List <CodeExpression> callParams = GenerateCallParamsJ2C(method); if (method.IsConstructor) { tgtMethod.ReturnType = new CodeTypeReference(typeof(void)); var call = new CodeObjectCreateExpression(RealType, callParams.ToArray()); tgtMethod.Statements.Add( new CodeVariableDeclarationStatement(RealType, realVariableName, call)); tgtMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(TypeReferenceEx(typeof(Convertor)), "InitProxy"), envVariable, objVariable, realVariable)); } else { CodeExpression targetObject; if (method.IsStatic) { targetObject = RealTypeEx; } else { CodeExpression expression = CreateConversionExpressionJ2C(type, objVariable); tgtMethod.Statements.Add( new CodeVariableDeclarationStatement(RealType, realVariableName, expression)); if (method.DeclaringType != type) { targetObject = new CodeCastExpression(method.DeclaringType.CLRReference, realVariable); } else { targetObject = realVariable; } } CodeExpression call; CodeExpression value = null; if (method.IsProperty) { if (method.IsVoid) { int last = callParams.Count - 1; value = callParams[last]; callParams.RemoveAt(last); } if (method.CLRProperty.GetIndexParameters().Length > 0) { call = new CodeIndexerExpression(targetObject, callParams.ToArray()); } else { call = new CodePropertyReferenceExpression(targetObject, method.CLRProperty.Name); } } else if (method.IsEvent) { int last = callParams.Count - 1; value = callParams[last]; if (method.IsCLRPropertyAdd) { call = new CodeEventReferenceExpression(targetObject, method.CLREvent.Name + "__event_add__"); } else { call = new CodeEventReferenceExpression(targetObject, method.CLREvent.Name + "__event_remove__"); } } else { call = new CodeMethodInvokeExpression(targetObject, method.CLRName, callParams.ToArray()); } CodeStatement callst; if (method.IsVoid) { if (method.IsProperty || method.IsEvent) { callst = new CodeAssignStatement(call, value); } else { callst = new CodeExpressionStatement(call); } } else { if (method.ReturnType.IsPrimitive) { if (method.ReturnType.JVMSubst != null) { call = new CodeCastExpression(method.ReturnType.CLRReference, call); } callst = new CodeAssignStatement(new CodeVariableReferenceExpression("__return"), call); tgtMethod.ReturnType = method.ReturnType.CLRReference; } else { CodeMethodInvokeExpression conversionExpression = CreateConversionExpressionC2J(method.ReturnType, call); callst = new CodeAssignStatement(new CodeVariableReferenceExpression("__return"), conversionExpression); tgtMethod.ReturnType = TypeReference(typeof(JniHandle)); } } tgtMethod.Statements.Add(callst); } }
protected override void GenerateEventReferenceExpression(CodeEventReferenceExpression e) { }
private void GenerateEventReferenceExpression(CodeEventReferenceExpression e, bool isRemove) { if (e.TargetObject != null) { GenerateExpression(e.TargetObject); if (isRemove == false) { Output.Write(".addEventListener("); } else { Output.Write(".removeEventListener("); } } OutputIdentifier("\"" + e.EventName + "\","); }
protected abstract void GenerateEventReferenceExpression(CodeEventReferenceExpression e);
public CodeAttachEventStatement(CodeEventReferenceExpression eventRef, CodeExpression listener) { _eventRef = eventRef; Listener = listener; }
public CodeRemoveEventStatement(CodeExpression targetObject, string eventName, CodeExpression listener) { _eventRef = new CodeEventReferenceExpression(targetObject, eventName); Listener = listener; }
static CodeStatement _ParseStatement(_PC pc, bool includeComments = false) { if (includeComments && (ST.lineComment == pc.SymbolId || ST.blockComment == pc.SymbolId)) { return(_ParseCommentStatement(pc)); } _SkipComments(pc); var pc2 = pc.GetLookAhead(); pc2.EnsureStarted(); CodeVariableDeclarationStatement vs = null; try { vs = _ParseVariableDeclaration(pc2); } catch { vs = null; } if (null != vs) { // advance _ParseVariableDeclaration(pc); return(vs); } pc2 = pc.GetLookAhead(); pc2.EnsureStarted(); CodeExpression e; try { e = _ParseExpression(pc2); } catch { e = null; } if (null != e) { _SkipComments(pc2); if (ST.semi == pc2.SymbolId) { pc2.Advance(); _ParseExpression(pc); _SkipComments(pc); pc.Advance(); // c# treats a=1; as an expression-statement using an assign expression, linguistically // so that's how we parsed it. However, CodeDOM has a special case object for this // called CodeAssignStatement. For maximum language portability, we don't want to rely // on assign expressions when we don't have to as they can get weird. So what we do is // whenever we parse one of these we detect it and turn it into an assign statement var bo = e as CodeBinaryOperatorExpression; if (null != bo && CodeBinaryOperatorType.Assign == bo.Operator) { return(new CodeAssignStatement(bo.Left, bo.Right)); } return(new CodeExpressionStatement(e)); } else if (ST.addAssign == pc2.SymbolId || ST.subAssign == pc2.SymbolId) { bool isAttach = ST.addAssign == pc2.SymbolId; _ParseExpression(pc); _SkipComments(pc); pc.Advance(); pc2.Advance(); _SkipComments(pc); var le = _ParseExpression(pc); _SkipComments(pc); if (pc.IsEnded) { throw new ArgumentException("Unterminated statement. Expecting ;", "input"); } pc.Advance(); var v = e as CodeVariableReferenceExpression; CodeEventReferenceExpression er = null; if (null != v) { er = new CodeEventReferenceExpression(null, v.VariableName); } else { var f = e as CodeFieldReferenceExpression; if (null != f) { er = new CodeEventReferenceExpression(f.TargetObject, f.FieldName); } } if (null == er) { throw new ArgumentNullException("The attach/remove target does not refer to a valid event", "input"); } er.UserData.Add("slang:unresolved", true); return(isAttach ? new CodeAttachEventStatement(er, le) as CodeStatement : new CodeRemoveEventStatement(er, le)); } } switch (pc.SymbolId) { case ST.keyword: switch (pc.Value) { case "if": return(_ParseIfStatement(pc)); case "goto": return(_ParseGotoStatement(pc)); case "for": return(_ParseForStatement(pc)); case "while": return(_ParseWhileStatement(pc)); case "return": return(_ParseReturnStatement(pc)); case "throw": return(_ParseThrowStatement(pc)); case "try": return(_ParseTryCatchFinallyStatement(pc)); case "var": case "bool": case "char": case "string": case "sbyte": case "byte": case "short": case "ushort": case "int": case "uint": case "long": case "ulong": case "float": case "double": case "decimal": return(_ParseVariableDeclaration(pc)); default: throw new NotSupportedException(string.Format("The keyword {0} is not supported", pc.Value)); } case ST.identifier: // we already know it isn't an expression var s = pc.Value; pc2 = pc.GetLookAhead(); pc2.EnsureStarted(); pc2.Advance(); if (ST.colon == pc2.SymbolId) { // CodeDOM for some reason wants us to attach a statement to a label. // we don't like that for a number of reasons so we don't do it. var ls = new CodeLabeledStatement(pc.Value); pc.Advance(); _SkipComments(pc); if (pc.IsEnded || ST.colon != pc.SymbolId) { throw new ArgumentException("Unterminated label. Expecting :", "input"); } pc.Advance(); return(ls); } throw new NotImplementedException("Not finished"); default: throw new ArgumentException(string.Format("Unexpected token {0} found statement.", pc.Value), "input"); } }
public CodeAttachEventStatement(CodeEventReferenceExpression eventRef, CodeExpression listener) {}
protected void GenerateExpression(CodeExpression e) { if (e == null) { throw new ArgumentNullException("e"); } CodeArgumentReferenceExpression argref = e as CodeArgumentReferenceExpression; if (argref != null) { GenerateArgumentReferenceExpression(argref); return; } CodeArrayCreateExpression mkarray = e as CodeArrayCreateExpression; if (mkarray != null) { GenerateArrayCreateExpression(mkarray); return; } CodeArrayIndexerExpression arrayidx = e as CodeArrayIndexerExpression; if (arrayidx != null) { GenerateArrayIndexerExpression(arrayidx); return; } CodeBaseReferenceExpression baseref = e as CodeBaseReferenceExpression; if (baseref != null) { GenerateBaseReferenceExpression(baseref); return; } CodeBinaryOperatorExpression binary = e as CodeBinaryOperatorExpression; if (binary != null) { GenerateBinaryOperatorExpression(binary); return; } CodeCastExpression cast = e as CodeCastExpression; if (cast != null) { GenerateCastExpression(cast); return; } CodeDelegateCreateExpression mkdel = e as CodeDelegateCreateExpression; if (mkdel != null) { GenerateDelegateCreateExpression(mkdel); return; } CodeDelegateInvokeExpression delinvoke = e as CodeDelegateInvokeExpression; if (delinvoke != null) { GenerateDelegateInvokeExpression(delinvoke); return; } CodeDirectionExpression direction = e as CodeDirectionExpression; if (direction != null) { GenerateDirectionExpression(direction); return; } CodeEventReferenceExpression eventref = e as CodeEventReferenceExpression; if (eventref != null) { GenerateEventReferenceExpression(eventref); return; } CodeFieldReferenceExpression fieldref = e as CodeFieldReferenceExpression; if (fieldref != null) { GenerateFieldReferenceExpression(fieldref); return; } CodeIndexerExpression idx = e as CodeIndexerExpression; if (idx != null) { GenerateIndexerExpression(idx); return; } CodeMethodInvokeExpression methodinv = e as CodeMethodInvokeExpression; if (methodinv != null) { GenerateMethodInvokeExpression(methodinv); return; } CodeMethodReferenceExpression methodref = e as CodeMethodReferenceExpression; if (methodref != null) { GenerateMethodReferenceExpression(methodref); return; } CodeObjectCreateExpression objref = e as CodeObjectCreateExpression; if (objref != null) { GenerateObjectCreateExpression(objref); return; } CodeParameterDeclarationExpression param = e as CodeParameterDeclarationExpression; if (param != null) { GenerateParameterDeclarationExpression(param); return; } CodePrimitiveExpression primitive = e as CodePrimitiveExpression; if (primitive != null) { GeneratePrimitiveExpression(primitive); return; } CodePropertyReferenceExpression propref = e as CodePropertyReferenceExpression; if (propref != null) { GeneratePropertyReferenceExpression(propref); return; } CodePropertySetValueReferenceExpression propset = e as CodePropertySetValueReferenceExpression; if (propset != null) { GeneratePropertySetValueReferenceExpression(propset); return; } CodeSnippetExpression snippet = e as CodeSnippetExpression; if (snippet != null) { GenerateSnippetExpression(snippet); return; } CodeThisReferenceExpression thisref = e as CodeThisReferenceExpression; if (thisref != null) { GenerateThisReferenceExpression(thisref); return; } CodeTypeOfExpression typeOf = e as CodeTypeOfExpression; if (typeOf != null) { GenerateTypeOfExpression(typeOf); return; } CodeTypeReferenceExpression typeref = e as CodeTypeReferenceExpression; if (typeref != null) { GenerateTypeReferenceExpression(typeref); return; } CodeVariableReferenceExpression varref = e as CodeVariableReferenceExpression; if (varref != null) { GenerateVariableReferenceExpression(varref); return; } throw new ArgumentException("Element type " + e + " is not supported.", "e"); }
protected abstract void GenerateEventReferenceExpression(CodeEventReferenceExpression e);
static void _Patch(CodeVariableReferenceExpression vr, CodeDomVisitContext ctx, CodeDomResolver resolver) { if (null != vr) { if ("NodeFlags" == vr.VariableName) { System.Diagnostics.Debugger.Break(); } var scope = resolver.GetScope(vr); if (scope.VariableTypes.ContainsKey(vr.VariableName)) { vr.UserData.Remove("slang:unresolved"); return; } // we need to replace it. if (scope.ArgumentTypes.ContainsKey(vr.VariableName)) { var a = new CodeArgumentReferenceExpression(vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, a); return; //args.Cancel = true; } else if (scope.FieldNames.Contains(vr.VariableName)) { CodeTypeReference tref; // find out where it belongs. if (scope.ThisTargets.Contains(vr.VariableName)) { var f = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, f); //return; } else if (scope.TypeTargets.TryGetValue(vr.VariableName, out tref)) { var f = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(tref), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, f); //return; } return; } else if (scope.MethodNames.Contains(vr.VariableName)) { CodeTypeReference tref; // find out where it belongs. if (scope.ThisTargets.Contains(vr.VariableName)) { var m = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, m); return; //args.Cancel = true; } if (scope.TypeTargets.TryGetValue(vr.VariableName, out tref)) { var m = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(tref), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, m); return; //args.Cancel = true; } } else if (scope.PropertyNames.Contains(vr.VariableName)) { CodeTypeReference tref; // find out where it belongs. if (scope.ThisTargets.Contains(vr.VariableName)) { var p = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, p); return; //args.Cancel = true; } else if (scope.TypeTargets.TryGetValue(vr.VariableName, out tref)) { var p = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tref), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, p); return; //args.Cancel = true; } } else if (scope.EventNames.Contains(vr.VariableName)) { CodeTypeReference tref; // find out where it belongs. if (scope.ThisTargets.Contains(vr.VariableName)) { var e = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, e); return; //args.Cancel = true; } else if (scope.TypeTargets.TryGetValue(vr.VariableName, out tref)) { var e = new CodeEventReferenceExpression(new CodeTypeReferenceExpression(tref), vr.VariableName); CodeDomVisitor.ReplaceTarget(ctx, e); return; //args.Cancel = true; } } return; } return; }