DefineEvent() публичный Метод

public DefineEvent ( string name, System attributes, System eventtype ) : System.Reflection.Emit.EventBuilder
name string
attributes System
eventtype System
Результат System.Reflection.Emit.EventBuilder
Пример #1
0
        public static void Generate(
            TypeBuilder typeBuilder,
            EventMetadata eventMetadata, 
            MethodBuilder addMethod,
            MethodBuilder removeMethod,
            MethodBuilder raiseMethod)
        {
            var @event = typeBuilder.DefineEvent(
                eventMetadata.Name,
                eventMetadata.EventAttributes,
                eventMetadata.EventHandlerType);

            if (addMethod != null)
            {
                @event.SetAddOnMethod(addMethod);
            }

            if (removeMethod != null)
            {
                @event.SetRemoveOnMethod(removeMethod);
            }

            if (raiseMethod != null)
            {
                @event.SetRaiseMethod(raiseMethod);
            }
        }
        private EventBuilder CreateProxyEventBuilder(TypeBuilder typeBuilder, EventInfo contractEvent)
        {
            var builder = typeBuilder.DefineEvent(contractEvent.Name, contractEvent.Attributes,
                                                  contractEvent.EventHandlerType);

            return builder;
        }
	protected void SetUp () {
		AssemblyName assemblyName = new AssemblyName();
		assemblyName.Name = GetType().FullName;

		AssemblyBuilder assembly 
			= Thread.GetDomain().DefineDynamicAssembly(
				assemblyName, AssemblyBuilderAccess.Run);

		module = assembly.DefineDynamicModule("module1");
		
	    tb = module.DefineType("class1", 
							   TypeAttributes.Public);

		eb = tb.DefineEvent ("event1", EventAttributes.None, typeof (AnEvent));
		mb = 
			tb.DefineMethod ("OnAnEvent",
							 MethodAttributes.Public, typeof (void),
							 new Type [] { typeof (AnEvent) });
		ILGenerator ilgen = mb.GetILGenerator();
		ilgen.Emit (OpCodes.Ret);

		// These two are required
		eb.SetAddOnMethod (mb);
		eb.SetRemoveOnMethod (mb);
	}
        public static void DefineEvent(TypeBuilder typeBuilder, EventInfo eventInfo,
            MethodBuilder addMethodBuilder, MethodBuilder removeMethodBuilder)
        {
            String eventName = eventInfo.DeclaringType.FullName + "." + eventInfo.Name;
            EventBuilder eventBuilder = typeBuilder.DefineEvent(eventName, EventAttributes.None, eventInfo.EventHandlerType);

            eventBuilder.SetAddOnMethod(addMethodBuilder);
            eventBuilder.SetRemoveOnMethod(removeMethodBuilder);
        }
 private EventBuilder ImplementEvent(TypeBuilder typeBuilder, EventInfo eventToImplement, Type targetInterface)
 {
     var eventBuilder = typeBuilder.DefineEvent(eventToImplement.Name, EventAttributes.None, eventToImplement.EventHandlerType);
     var addMethodInfo = eventToImplement.GetAddMethod();
     var removeMethodInfo = eventToImplement.GetRemoveMethod();
     var addMethodBuilder = ImplementMethod(typeBuilder, addMethodInfo, targetInterface);
     var removeMethodBuilder = ImplementMethod(typeBuilder, removeMethodInfo, targetInterface);
     eventBuilder.SetAddOnMethod(addMethodBuilder);
     eventBuilder.SetRemoveOnMethod(removeMethodBuilder);
     return eventBuilder;
 }
        public void Build(TypeBuilder builder, Type contractType)
        {
            builder.AddInterfaceImplementation(typeof(IAutoNotifyPropertyChanged));

            FieldBuilder addPropertyChangedField = builder.DefineField("PropertyChanged", typeof (PropertyChangingEventHandler), FieldAttributes.Private);

            MethodBuilder addMethod = DefineAddOnMethod(builder, addPropertyChangedField);
            MethodBuilder removeMethod = DefineRemoveOnMethod(builder, addPropertyChangedField);
            MethodBuilder notifyPropertyChangedMethod = DefineRaiseMethod(builder, addPropertyChangedField);

            EventBuilder pcevent = builder.DefineEvent("PropertyChanged", EventAttributes.None, typeof(PropertyChangedEventHandler));
            pcevent.SetRaiseMethod(notifyPropertyChangedMethod);
            pcevent.SetAddOnMethod(addMethod);
            pcevent.SetRemoveOnMethod(removeMethod);
        }
        public static void Define(TypeBuilder typeB, Interface iface)
        {
            foreach (Method declMethod in iface.Methods)
                DefineMethod (typeB, declMethod.Name, ifaceMethAttr, declMethod.Arguments, false);

            if (iface.Properties != null)
            foreach (NDesk.DBus.Introspection.Property prop in iface.Properties) {
                Type propType = new Signature (prop.Type).ToType ();

                PropertyBuilder prop_builder = typeB.DefineProperty (prop.Name, PropertyAttributes.None, propType, Type.EmptyTypes);

                if (prop.Access == propertyAccess.read || prop.Access == propertyAccess.readwrite)
                    prop_builder.SetGetMethod (typeB.DefineMethod ("get_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, propType, Type.EmptyTypes));

                if (prop.Access == propertyAccess.write || prop.Access == propertyAccess.readwrite)
                    prop_builder.SetSetMethod (typeB.DefineMethod ("set_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {propType}));
            }

            if (iface.Signals != null)
            foreach (NDesk.DBus.Introspection.Signal signal in iface.Signals) {
                Type eventType = DefineHandler (modBdef, signal);

                EventBuilder event_builder = typeB.DefineEvent (signal.Name, EventAttributes.None, eventType);

                event_builder.SetAddOnMethod (typeB.DefineMethod ("add_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType}));

                event_builder.SetRemoveOnMethod (typeB.DefineMethod ("remove_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType}));
            }

            //apply InterfaceAttribute
            ConstructorInfo interfaceAttributeCtor = typeof (InterfaceAttribute).GetConstructor(new Type[] {typeof (string)});

            CustomAttributeBuilder cab = new CustomAttributeBuilder (interfaceAttributeCtor, new object[] {iface.Name});

            typeB.SetCustomAttribute (cab);
        }
Пример #8
0
		public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
		{
			MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);

			// And now store the values in our own fields.
			
			declaring_type = type_builder;

			reflected_type = type_builder;
			
			attributes = event_attr;
			this.name = name;
			my_event = ev;
			this.event_type = event_type;
		}
Пример #9
0
        private static void MakeEvent(ModuleBuilder builder, EventInfo info, TypeBuilder typeBuilder, Type contextType, bool defaultImp)
        {
            var tName = info.Name;
            var tAddMethod = info.GetAddMethod();
            var tRemoveMethod = info.GetRemoveMethod();
            var tReturnType = info.EventHandlerType;

            var tCallSiteInvokeName = string.Format("Impromptu_Callsite_{1}_{0}", Guid.NewGuid().ToString("N"), tName);
            var tCStp = DefineBuilderForCallSite(builder, tCallSiteInvokeName);

            var tInvokeIsEvent = "Invoke_IsEvent";
            var tInvokeIseventFuncType = tCStp.DefineCallsiteField(tInvokeIsEvent, typeof (bool));

            var tInvokeAddAssign = "Invoke_AddAssign";
            var tInvokeAddAssignFuncType = tCStp.DefineCallsiteField(tInvokeAddAssign, typeof (object), tReturnType);

            var tInvokeSubtractAssign = "Invoke_SubtractAssign";
            var tInvokeSubtractAssignFuncType = tCStp.DefineCallsiteField(tInvokeSubtractAssign, typeof (object), tReturnType);

            var tAddParamTypes = tRemoveMethod.GetParameters().Select(it => it.ParameterType).ToArray();
            var tInvokeAdd = "Invoke_Add";
            var tInvokeAddFuncType = tCStp.DefineCallsiteField(tInvokeAdd, typeof (object), tAddParamTypes);

            var tRemoveParamTypes = tRemoveMethod.GetParameters().Select(it => it.ParameterType).ToArray();
            var tInvokeRemove = "Invoke_Remove";
            var tInvokeRemoveFuncType = tCStp.DefineCallsiteField(tInvokeRemove, typeof (object), tRemoveParamTypes);

            var tInvokeGet = "Invoke_Get";
            var tInvokeGetFuncType = tCStp.DefineCallsiteField(tInvokeGet, typeof (object));

            var tInvokeSet = "Invoke_Set";

            var tInvokeSetFuncType = tCStp.DefineCallsiteField(tInvokeSet, typeof (object), typeof (object));

            var tCallSite = tCStp.CreateType();

            var tMp = typeBuilder.DefineEvent(tName, EventAttributes.None, tReturnType);

            //AddMethod
            var tPublicPrivate = MethodAttributes.Public;
            var tAddPrefixName = tAddMethod.Name;
            if (!defaultImp) {
                tAddPrefixName = String.Format("{0}.{1}", info.DeclaringType.FullName, tAddPrefixName);

                tPublicPrivate = MethodAttributes.Private;
            }

            var tAddBuilder = typeBuilder.DefineMethod(tAddPrefixName,
                tPublicPrivate | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.NewSlot,
                typeof (void),
                tAddParamTypes);

            if (!defaultImp) {
                typeBuilder.DefineMethodOverride(tAddBuilder, info.GetAddMethod());
            }

            foreach (var tParam in tAddMethod.GetParameters()) {
                tAddBuilder.DefineParameter(tParam.Position + 1, AttributesForParam(tParam), tParam.Name);
            }

            var tIlGen = tAddBuilder.GetILGenerator();

            var tIsEventField = tCallSite.GetFieldEvenIfGeneric(tInvokeIsEvent);

            using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tIsEventField))) {
                tIlGen.EmitDynamicIsEventBinder(CSharpBinderFlags.None, tName, contextType);
                tIlGen.EmitCallsiteCreate(tInvokeIseventFuncType);
                tIlGen.Emit(OpCodes.Stsfld, tIsEventField);
            }

            var tSetField = tCallSite.GetFieldEvenIfGeneric(tInvokeSet);
            var tGetField = tCallSite.GetFieldEvenIfGeneric(tInvokeGet);

            using (tIlGen.EmitBranchTrue(
                load => load.EmitInvocation(
                    target => target.EmitInvocation(
                        t => t.Emit(OpCodes.Ldsfld, tIsEventField),
                        i => i.Emit(OpCodes.Ldfld, tIsEventField.FieldType.GetFieldEvenIfGeneric("Target"))
                        ),
                    invoke => invoke.EmitCallInvokeFunc(tInvokeIseventFuncType),
                    param => param.Emit(OpCodes.Ldsfld, tIsEventField),
                    param => param.EmitInvocation(
                        t => t.Emit(OpCodes.Ldarg_0),
                        i => i.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod())
                        )
                    )
                )
                ) //if IsEvent Not True
            {
                using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tSetField))) {
                    tIlGen.EmitDynamicSetBinderDynamicParams(CSharpBinderFlags.ValueFromCompoundAssignment, tName, contextType, typeof (Object));
                    tIlGen.EmitCallsiteCreate(tInvokeSetFuncType);
                    tIlGen.Emit(OpCodes.Stsfld, tSetField);
                }

                var tAddAssigneField = tCallSite.GetFieldEvenIfGeneric(tInvokeAddAssign);

                using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tAddAssigneField))) {
                    tIlGen.EmitDynamicBinaryOpBinder(CSharpBinderFlags.None, ExpressionType.AddAssign, contextType, tReturnType);
                    tIlGen.EmitCallsiteCreate(tInvokeAddAssignFuncType);
                    tIlGen.Emit(OpCodes.Stsfld, tAddAssigneField);
                }

                using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tGetField))) {
                    tIlGen.EmitDynamicGetBinder(CSharpBinderFlags.None, tName, contextType);
                    tIlGen.EmitCallsiteCreate(tInvokeGetFuncType);
                    tIlGen.Emit(OpCodes.Stsfld, tGetField);
                }

                tIlGen.Emit(OpCodes.Ldsfld, tSetField);
                tIlGen.Emit(OpCodes.Ldfld, tSetField.FieldType.GetFieldEvenIfGeneric("Target"));
                tIlGen.Emit(OpCodes.Ldsfld, tSetField);
                tIlGen.Emit(OpCodes.Ldarg_0);
                tIlGen.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod());

                tIlGen.Emit(OpCodes.Ldsfld, tAddAssigneField);
                tIlGen.Emit(OpCodes.Ldfld, tAddAssigneField.FieldType.GetFieldEvenIfGeneric("Target"));
                tIlGen.Emit(OpCodes.Ldsfld, tAddAssigneField);

                tIlGen.Emit(OpCodes.Ldsfld, tGetField);
                tIlGen.Emit(OpCodes.Ldfld, tGetField.FieldType.GetFieldEvenIfGeneric("Target"));
                tIlGen.Emit(OpCodes.Ldsfld, tGetField);
                tIlGen.Emit(OpCodes.Ldarg_0);
                tIlGen.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod());

                tIlGen.EmitCallInvokeFunc(tInvokeGetFuncType);

                tIlGen.Emit(OpCodes.Ldarg_1);
                tIlGen.EmitCallInvokeFunc(tInvokeAddAssignFuncType);

                tIlGen.EmitCallInvokeFunc(tInvokeSetFuncType);
                tIlGen.Emit(OpCodes.Pop);
                tIlGen.Emit(OpCodes.Ret);
            }

            var tAddCallSiteField = tCallSite.GetFieldEvenIfGeneric(tInvokeAdd);

            using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tAddCallSiteField))) {
                tIlGen.EmitDynamicMethodInvokeBinder(
                    CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded,
                    tAddMethod.Name,
                    contextType,
                    tAddMethod.GetParameters(),
                    Enumerable.Repeat(default(string),
                        tAddParamTypes.Length));
                tIlGen.EmitCallsiteCreate(tInvokeAddFuncType);
                tIlGen.Emit(OpCodes.Stsfld, tAddCallSiteField);
            }
            tIlGen.Emit(OpCodes.Ldsfld, tAddCallSiteField);
            tIlGen.Emit(OpCodes.Ldfld, tAddCallSiteField.FieldType.GetFieldEvenIfGeneric("Target"));
            tIlGen.Emit(OpCodes.Ldsfld, tAddCallSiteField);
            tIlGen.Emit(OpCodes.Ldarg_0);
            tIlGen.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod());
            for (var i = 1; i <= tAddParamTypes.Length; i++) {
                tIlGen.EmitLoadArgument(i);
            }
            tIlGen.EmitCallInvokeFunc(tInvokeAddFuncType);
            tIlGen.Emit(OpCodes.Pop);
            tIlGen.Emit(OpCodes.Ret);

            tMp.SetAddOnMethod(tAddBuilder);

            var tRemovePrefixName = tRemoveMethod.Name;
            if (!defaultImp) {
                tRemovePrefixName = String.Format("{0}.{1}", info.DeclaringType.FullName, tRemovePrefixName);
            }

            //Remove Method
            var tRemoveBuilder = typeBuilder.DefineMethod(tRemovePrefixName,
                tPublicPrivate | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.NewSlot,
                typeof (void),
                tAddParamTypes);
            if (!defaultImp) {
                typeBuilder.DefineMethodOverride(tRemoveBuilder, info.GetRemoveMethod());
            }

            foreach (var tParam in tRemoveMethod.GetParameters()) {
                tRemoveBuilder.DefineParameter(tParam.Position + 1, AttributesForParam(tParam), tParam.Name);
            }

            tIlGen = tRemoveBuilder.GetILGenerator();

            using (tIlGen.EmitBranchTrue(load => load.Emit(OpCodes.Ldsfld, tIsEventField))) {
                tIlGen.EmitDynamicIsEventBinder(CSharpBinderFlags.None, tName, contextType);
                tIlGen.EmitCallsiteCreate(tInvokeIseventFuncType);
                tIlGen.Emit(OpCodes.Stsfld, tIsEventField);
            }

            using (tIlGen.EmitBranchTrue(
                load => load.EmitInvocation(
                    target => target.EmitInvocation(
                        t => t.Emit(OpCodes.Ldsfld, tIsEventField),
                        i => i.Emit(OpCodes.Ldfld, tIsEventField.FieldType.GetFieldEvenIfGeneric("Target"))
                        ),
                    invoke => invoke.EmitCallInvokeFunc(tInvokeIseventFuncType),
                    param => param.Emit(OpCodes.Ldsfld, tIsEventField),
                    param => param.EmitInvocation(
                        t => t.Emit(OpCodes.Ldarg_0),
                        i => i.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod())
                        )
                    )
                )
                ) //if IsEvent Not True
            {
                using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tSetField))) {
                    tIlGen.EmitDynamicSetBinderDynamicParams(CSharpBinderFlags.ValueFromCompoundAssignment, tName, contextType, tReturnType);
                    tIlGen.EmitCallsiteCreate(tInvokeSetFuncType);
                    tIlGen.Emit(OpCodes.Stsfld, tSetField);
                }

                var tSubrtractAssignField = tCallSite.GetFieldEvenIfGeneric(tInvokeSubtractAssign);

                using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tSubrtractAssignField))) {
                    tIlGen.EmitDynamicBinaryOpBinder(CSharpBinderFlags.None, ExpressionType.SubtractAssign, contextType, tReturnType);
                    tIlGen.EmitCallsiteCreate(tInvokeSubtractAssignFuncType);
                    tIlGen.Emit(OpCodes.Stsfld, tSubrtractAssignField);
                }

                using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tGetField))) {
                    tIlGen.EmitDynamicGetBinder(CSharpBinderFlags.None, tName, contextType);
                    tIlGen.EmitCallsiteCreate(tInvokeGetFuncType);
                    tIlGen.Emit(OpCodes.Stsfld, tGetField);
                }

                tIlGen.Emit(OpCodes.Ldsfld, tSetField);
                tIlGen.Emit(OpCodes.Ldfld, tSetField.FieldType.GetFieldEvenIfGeneric("Target"));
                tIlGen.Emit(OpCodes.Ldsfld, tSetField);
                tIlGen.Emit(OpCodes.Ldarg_0);
                tIlGen.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod());

                tIlGen.Emit(OpCodes.Ldsfld, tSubrtractAssignField);
                tIlGen.Emit(OpCodes.Ldfld, tSubrtractAssignField.FieldType.GetFieldEvenIfGeneric("Target"));
                tIlGen.Emit(OpCodes.Ldsfld, tSubrtractAssignField);

                tIlGen.Emit(OpCodes.Ldsfld, tGetField);
                tIlGen.Emit(OpCodes.Ldfld, tGetField.FieldType.GetFieldEvenIfGeneric("Target"));
                tIlGen.Emit(OpCodes.Ldsfld, tGetField);
                tIlGen.Emit(OpCodes.Ldarg_0);
                tIlGen.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod());

                tIlGen.EmitCallInvokeFunc(tInvokeGetFuncType);

                tIlGen.Emit(OpCodes.Ldarg_1);
                tIlGen.EmitCallInvokeFunc(tInvokeSubtractAssignFuncType);

                tIlGen.EmitCallInvokeFunc(tInvokeSetFuncType);

                tIlGen.Emit(OpCodes.Pop);
                tIlGen.Emit(OpCodes.Ret);
            }

            var tRemoveCallSiteField = tCallSite.GetFieldEvenIfGeneric(tInvokeRemove);
            using (tIlGen.EmitBranchTrue(gen => gen.Emit(OpCodes.Ldsfld, tRemoveCallSiteField))) {
                tIlGen.EmitDynamicMethodInvokeBinder(
                    CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded,
                    tRemoveMethod.Name,
                    contextType,
                    tRemoveMethod.GetParameters(),
                    Enumerable.Repeat(default(string),
                        tRemoveParamTypes.Length));
                tIlGen.EmitCallsiteCreate(tInvokeRemoveFuncType);
                tIlGen.Emit(OpCodes.Stsfld, tRemoveCallSiteField);
            }
            tIlGen.Emit(OpCodes.Ldsfld, tRemoveCallSiteField);
            tIlGen.Emit(OpCodes.Ldfld, tRemoveCallSiteField.FieldType.GetFieldEvenIfGeneric("Target"));
            tIlGen.Emit(OpCodes.Ldsfld, tRemoveCallSiteField);
            tIlGen.Emit(OpCodes.Ldarg_0);
            tIlGen.Emit(OpCodes.Call, typeof (ActLikeProxy).GetProperty("Original").GetGetMethod());
            tIlGen.Emit(OpCodes.Ldarg_1);
            tIlGen.EmitCallInvokeFunc(tInvokeRemoveFuncType);
            tIlGen.Emit(OpCodes.Pop);
            tIlGen.Emit(OpCodes.Ret);

            tMp.SetRemoveOnMethod(tRemoveBuilder);
        }
Пример #10
0
        /// <summary>
        /// Compiles the type that is being built and returns its run-time Type.
        /// If you want to create instances directly, see the GetConstructorDelegate.
        /// </summary>
        public Type Compile()
        {
            if (_compiledType == null)
            {
                _CheckThread();

                _delegates = new Delegate[_methods.Count];

                var methodBuilders = new Dictionary <string, MethodBuilder>();
                int index          = -1;
                foreach (var method in _methods)
                {
                    index++;
                    var methodBuilder = _Compile(method, index);
                    methodBuilders[method.Name] = methodBuilder;
                }

                foreach (var property in _properties.Values)
                {
                    string name            = property.Name;
                    var    propertyBuilder = _type.DefineProperty(name, PropertyAttributes.None, property.PropertyType, Type.EmptyTypes);
                    propertyBuilder.SetGetMethod(methodBuilders["get_" + name]);
                    propertyBuilder.SetSetMethod(methodBuilders["set_" + name]);
                }

                foreach (var eventInfo in _events.Values)
                {
                    string name         = eventInfo.Name;
                    var    eventBuilder = _type.DefineEvent(name, EventAttributes.None, eventInfo.Type);

                    string addName    = "add_" + name;
                    string removeName = "remove_" + name;

                    var addMethod    = methodBuilders[addName];
                    var removeMethod = methodBuilders[removeName];
                    eventBuilder.SetAddOnMethod(addMethod);
                    eventBuilder.SetRemoveOnMethod(removeMethod);

                    foreach (var interfaceType in _interfaceTypes)
                    {
                        var method = interfaceType.GetMethod(addName);
                        if (method != null)
                        {
                            _type.DefineMethodOverride(addMethod, method);
                        }

                        method = interfaceType.GetMethod(removeName);
                        if (method != null)
                        {
                            _type.DefineMethodOverride(removeMethod, method);
                        }
                    }
                }

                var compiledType = _type.CreateType();

                var thisExpression = Expression.Parameter(compiledType, "this");
                var fields         = _fields.ToArray();
                foreach (var fieldPair in fields)
                {
                    var    leftPair   = fieldPair.Key;
                    var    field      = leftPair.Key;
                    var    rightPair  = fieldPair.Value;
                    string fieldName  = rightPair.Value;
                    var    expression = Expression.MakeMemberAccess(thisExpression, compiledType.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic));
                    _fields[leftPair] = new KeyValuePair <MemberExpression, string>(expression, fieldName);
                }

                index = -1;
                foreach (var method in _methods)
                {
                    index++;

                    if (method._respectVisibility)
                    {
                        continue;
                    }

                    if (!method.IsStatic)
                    {
                        var firstParameter = method._parameters.Keys.First();
                        method._parameters[firstParameter] = thisExpression;
                    }

                    var compiledMethod = method._Compile(null, null);
                    _delegates[index] = compiledMethod;
                }

                var delegatesField = compiledType.GetField(".delegates", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                delegatesField.SetValue(null, _delegates);

                _compiledType = compiledType;
            }

            return(_compiledType);
        }
Пример #11
0
        /************************************************************************/
        /************************************************************************/
        private static FieldBuilder CreatePropertyChangedEvent(TypeBuilder typeBuilder)
        {
            // public event PropertyChangedEventHandler PropertyChanged;

            FieldBuilder eventField = typeBuilder.DefineField("PropertyChanged", typeof(PropertyChangedEventHandler), FieldAttributes.Private);
            EventBuilder eventBuilder = typeBuilder.DefineEvent("PropertyChanged", EventAttributes.None, typeof(PropertyChangedEventHandler));

            eventBuilder.SetAddOnMethod(CreateAddRemoveMethod(typeBuilder, eventField, true));
            eventBuilder.SetRemoveOnMethod(CreateAddRemoveMethod(typeBuilder, eventField, false));

            return eventField;
        }
Пример #12
0
        public static void Define(TypeBuilder typeB, Interface iface)
        {
            foreach (Method declMethod in iface.Methods) {

                //MethodBuilder method_builder = typeB.DefineMethod (declMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, declMethod.ReturnType, Mapper.GetTypes (ArgDirection.In, declMethod.GetParameters ()));

                List<Type> parms = new List<Type> ();

                if (declMethod.Arguments != null)
                    foreach (Argument arg in declMethod.Arguments) {
                        if (arg.Direction == Introspection.ArgDirection.@in)
                            parms.Add (new Signature (arg.Type).ToType ());
                        //if (arg.Direction == Introspection.ArgDirection.@out)
                        //	parms.Add (new Signature (arg.Type).ToType ().MakeByRefType ());
                    }

                Signature outSig = Signature.Empty;
                //this just takes the last out arg and uses is as the return type
                if (declMethod.Arguments != null)
                    foreach (Argument arg in declMethod.Arguments)
                        if (arg.Direction == Introspection.ArgDirection.@out)
                            outSig = new Signature (arg.Type);

                Type retType = outSig == Signature.Empty ? typeof (void) : outSig.ToType ();

                MethodBuilder method_builder = typeB.DefineMethod (declMethod.Name, ifaceMethAttr, retType, parms.ToArray ());

                //define the parameter attributes and names
                if (declMethod.Arguments != null) {
                    int argNum = 0;

                    foreach (Argument arg in declMethod.Arguments) {
                        if (arg.Direction == Introspection.ArgDirection.@in)
                            method_builder.DefineParameter (++argNum, ParameterAttributes.In, arg.Name);
                        //if (arg.Direction == Introspection.ArgDirection.@out)
                        //	method_builder.DefineParameter (++argNum, ParameterAttributes.Out, arg.Name);
                    }
                }
            }

            if (iface.Properties != null)
            foreach (NDesk.DBus.Introspection.Property prop in iface.Properties) {
                Type propType = new Signature (prop.Type).ToType ();

                PropertyBuilder prop_builder = typeB.DefineProperty (prop.Name, PropertyAttributes.None, propType, Type.EmptyTypes);

                if (prop.Access == propertyAccess.read || prop.Access == propertyAccess.readwrite)
                    prop_builder.SetGetMethod (typeB.DefineMethod ("get_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, propType, Type.EmptyTypes));

                if (prop.Access == propertyAccess.write || prop.Access == propertyAccess.readwrite)
                    prop_builder.SetSetMethod (typeB.DefineMethod ("set_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {propType}));
            }

            if (iface.Signals != null)
            foreach (NDesk.DBus.Introspection.Signal signal in iface.Signals) {
                //Type eventType = typeof (EventHandler);
                Type eventType = typeof (VoidHandler);

                EventBuilder event_builder = typeB.DefineEvent (signal.Name, EventAttributes.None, eventType);

                event_builder.SetAddOnMethod (typeB.DefineMethod ("add_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType}));

                event_builder.SetRemoveOnMethod (typeB.DefineMethod ("remove_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType}));
            }

            //apply InterfaceAttribute
            ConstructorInfo interfaceAttributeCtor = typeof (InterfaceAttribute).GetConstructor(new Type[] {typeof (string)});

            CustomAttributeBuilder cab = new CustomAttributeBuilder (interfaceAttributeCtor, new object[] {iface.Name});

            typeB.SetCustomAttribute (cab);
        }
        private void GenerateEvents(List<string> usedNames, Type interfaceType, TypeBuilder tb, List<MethodInfo> propAccessors)
        {
            foreach (EventInfo eventInfo in interfaceType.GetEvents(BindingFlags.Instance | BindingFlags.Public))
            {
                if (usedNames.Contains(eventInfo.Name))
                {
                    throw new NotSupportedException(string.Format("Error in interface {1}! Event name '{0}' already used in other child interface!", eventInfo.Name, interfaceType.Name)); //LOCSTR
                }
                else
                {
                    usedNames.Add(eventInfo.Name);
                }

                EventBuilder eb = tb.DefineEvent(eventInfo.Name, eventInfo.Attributes, eventInfo.EventHandlerType);
                FieldBuilder ef = tb.DefineField(string.Concat("_", eventInfo.Name), eventInfo.EventHandlerType, FieldAttributes.Private);

                //add
                {
                    MethodInfo addMethodInfo = eventInfo.GetAddMethod();
                    propAccessors.Add(addMethodInfo);
                    MethodBuilder getMb = tb.DefineMethod(addMethodInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new Type[] { eventInfo.EventHandlerType });
                    ILGenerator ilGenerator = getMb.GetILGenerator();

                    EmitEventAdd(ilGenerator, eventInfo, ef);

                    tb.DefineMethodOverride(getMb, addMethodInfo);
                }
                //remove
                {
                    MethodInfo removeMethodInfo = eventInfo.GetRemoveMethod();
                    propAccessors.Add(removeMethodInfo);
                    MethodBuilder getMb = tb.DefineMethod(removeMethodInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new Type[] { eventInfo.EventHandlerType });
                    ILGenerator ilGenerator = getMb.GetILGenerator();

                    EmitEventRemove(ilGenerator, eventInfo, ef);

                    tb.DefineMethodOverride(getMb, removeMethodInfo);

                }
            }
        }
Пример #14
0
        private static EventBuilder CreateEvent(TypeBuilder dest, EventInfo ev)
        {
            MethodBuilder add = null, remove = null;

            var mi = ev.GetAddMethod();
            if (mi != null)
            {
                add = CreateMethodCopy(dest, mi);
            }

            mi = ev.GetRemoveMethod();
            if (mi != null)
            {
                remove = CreateMethodCopy(dest, mi);
            }

            var evt = dest.DefineEvent(ev.Name, ev.Attributes, ev.EventHandlerType);
            if (add != null)
            {
                evt.SetAddOnMethod(add);
            }

            if (remove != null)
            {
                evt.SetRemoveOnMethod(remove);
            }

            return evt;
        }
Пример #15
0
        private EventBuilder DefineEvent(TypeBuilder typeBuilder, Cci.IEventDefinition eventDef)
        {
            EventAttributes attrs = (EventAttributes)Cci.MetadataWriter.GetEventFlags(eventDef);
            Type type = ResolveType(eventDef.GetType(_context));

            // Event, EventMap
            var eventBuilder = typeBuilder.DefineEvent(eventDef.Name, attrs, type);

            // MethodSemantics
            foreach (var accessor in eventDef.Accessors)
            {
                var accessorDef = (Cci.IMethodDefinition)accessor.AsDefinition(_context);
                var accessorBuilder = _methodBuilders[accessorDef];

                if (accessor == eventDef.Adder)
                {
                    eventBuilder.SetAddOnMethod(accessorBuilder);
                }
                else if (accessor == eventDef.Remover)
                {
                    eventBuilder.SetRemoveOnMethod(accessorBuilder);
                }
                else if (accessor == eventDef.Caller)
                {
                    eventBuilder.SetRaiseMethod(accessorBuilder);
                }
                else
                {
                    eventBuilder.AddOtherMethod(accessorBuilder);
                }
            }

            return eventBuilder;
        }
Пример #16
0
		void DefineEvent(TypeBuilder typeBuilder, Event node)
		{
			var builder = typeBuilder.DefineEvent(node.Name, EventAttributes.None, GetSystemType(node.Type));
			builder.SetAddOnMethod(DefineEventMethod(typeBuilder, node.Add));
			builder.SetRemoveOnMethod(DefineEventMethod(typeBuilder, node.Remove));
			if (node.Raise != null)
				builder.SetRaiseMethod(DefineEventMethod(typeBuilder, node.Raise));
			SetBuilder(node, builder);
		}
Пример #17
0
        private static FieldBuilder AddEvent(TypeBuilder typeBuilder, string eventName, Type eventHandlerType)
        {
            EventBuilder eventBuilder = typeBuilder.DefineEvent(eventName, EventAttributes.None, eventHandlerType);

            FieldBuilder backingField = typeBuilder.DefineField(eventName, eventHandlerType, FieldAttributes.Private);

            MethodBuilder addMethod = typeBuilder.DefineMethod("add_" + eventName,
                                                                MethodAttributes.Public | MethodAttributes.HideBySig |
                                                                MethodAttributes.SpecialName,
                                                                CallingConventions.Standard, typeof(void), new [] { eventHandlerType });

            ILGenerator generator = addMethod.GetILGenerator();

            generator.DeclareLocal(eventHandlerType);
            generator.DeclareLocal(eventHandlerType);
            generator.DeclareLocal(eventHandlerType);
            generator.DeclareLocal(typeof(bool));

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, backingField);
            generator.Emit(OpCodes.Stloc_0);
            Label loop = generator.DefineLabel();
            generator.MarkLabel(loop);
            generator.Emit(OpCodes.Ldloc_0);
            generator.Emit(OpCodes.Stloc_1);
            generator.Emit(OpCodes.Ldloc_1);
            generator.Emit(OpCodes.Ldarg_1);
            generator.Emit(OpCodes.Call, typeof(Delegate).GetMethod("Combine", new []{typeof(Delegate), typeof(Delegate)}));
            generator.Emit(OpCodes.Castclass, eventHandlerType);
            generator.Emit(OpCodes.Stloc_2);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldflda, backingField);
            generator.Emit(OpCodes.Ldloc_2);
            generator.Emit(OpCodes.Ldloc_1);

            MethodInfo m = GetGenericMethod(typeof(Interlocked), "CompareExchange", new [] { eventHandlerType }, new [] { eventHandlerType, eventHandlerType, eventHandlerType });

            generator.Emit(OpCodes.Call, m);
            generator.Emit(OpCodes.Stloc_0);
            generator.Emit(OpCodes.Ldloc_0);
            generator.Emit(OpCodes.Ldloc_1);
            generator.Emit(OpCodes.Ceq);
            generator.Emit(OpCodes.Ldc_I4_0);
            generator.Emit(OpCodes.Ceq);
            generator.Emit(OpCodes.Stloc_3);
            generator.Emit(OpCodes.Ldloc_3);
            generator.Emit(OpCodes.Brtrue_S, loop);

            generator.Emit(OpCodes.Ldstr, "ADD...");
            EmitConsoleWriteLine(generator);

            generator.Emit(OpCodes.Ret);

            MethodBuilder removeMethod = typeBuilder.DefineMethod("remove_" + eventName,
                                                                MethodAttributes.Public | MethodAttributes.HideBySig |
                                                                MethodAttributes.SpecialName,
                                                                CallingConventions.Standard, typeof(void), new[] { eventHandlerType });

            generator = removeMethod.GetILGenerator();

            generator.Emit(OpCodes.Ldstr, "REMOVE...");

            generator.Emit(OpCodes.Ret);

            eventBuilder.SetAddOnMethod(addMethod);
            eventBuilder.SetRemoveOnMethod(removeMethod);

            return backingField;
        }
	    /// <summary>
	    /// Implements the specified event.
	    /// </summary>
	    /// <param name="typeBuilder">The type builder to use.</param>
	    /// <param name="type">The type the event is defined on.</param>
	    /// <param name="evt">The event to proxy.</param>
	    /// <param name="methodMap">The implemented methods map.</param>
	    protected virtual void ImplementEvent(TypeBuilder typeBuilder, Type type, EventInfo evt, IDictionary<string, MethodBuilder> methodMap)
		{
            MethodBuilder addOnMethod;
            methodMap.TryGetValue("add_" + evt.Name, out addOnMethod);
            MethodBuilder removeOnMethod;
	        methodMap.TryGetValue("remove_" + evt.Name, out removeOnMethod);

            if (addOnMethod != null && removeOnMethod != null)
            {
                string eventName = (addOnMethod.IsPrivate) 
                    ? addOnMethod.DeclaringType.FullName + "." + evt.Name 
                    : evt.Name;

                EventBuilder eb = typeBuilder.DefineEvent(
                    eventName, EventAttributes.None, evt.EventHandlerType);
                
                // set add/remove methods
                eb.SetAddOnMethod(addOnMethod);
                eb.SetRemoveOnMethod(removeOnMethod);
            }		
		}
        static void BuildEvent(TypeBuilder type, Type viewType, EventInfo eventInfo)
        {
            var addMethod = BuildEventAddMethod(type, viewType, eventInfo);
            var removeMethod = BuildEventRemoveMethod(type, viewType, eventInfo);

            if (eventInfo.EventHandlerType == null)
            {
                throw new ArgumentException(string.Format(
                    CultureInfo.InvariantCulture,
                    "The supplied event {0} from {1} does not have the event handler type specified.",
                    eventInfo.Name,
                    eventInfo.ReflectedType.Name),
                    "eventInfo");
            }

            var @event = type.DefineEvent(
                eventInfo.Name,
                eventInfo.Attributes,
                eventInfo.EventHandlerType);

            @event.SetAddOnMethod(addMethod);
            @event.SetRemoveOnMethod(removeMethod);
        }
Пример #20
0
        void DefineEvent(TypeBuilder typeBuilder, Event node)
        {
            EventBuilder builder = typeBuilder.DefineEvent(node.Name,
                                                           EventAttributes.None,
                                                           GetSystemType(node.Type));
            //MethodAttributes attribs = GetPropertyMethodAttributes(node);
            MethodAttributes baseAttributes = MethodAttributes.SpecialName;
            builder.SetAddOnMethod(DefineMethod(typeBuilder, node.Add, baseAttributes|GetMethodAttributes(node.Add)));
            builder.SetRemoveOnMethod(DefineMethod(typeBuilder, node.Remove, baseAttributes|GetMethodAttributes(node.Remove)));

            if (null != node.Raise)
            {
                builder.SetRaiseMethod(DefineMethod(typeBuilder, node.Raise, baseAttributes|GetMethodAttributes(node.Raise)));
            }

            SetBuilder(node, builder);
        }
Пример #21
0
 public FieldBuilder BuildEvent(TypeBuilder type, MethodInfo method, Type delegateType)
 {
     EventBuilder e = type.DefineEvent("_" + method.Name, EventAttributes.None, delegateType);
     Type[] types = new Type[] { typeof(Delegate), typeof(Delegate) };
     FieldBuilder field = type.DefineField("_" + method.Name, delegateType, FieldAttributes.Private);
     string[] nameprefixes = new string[] { "add", "remove" };
     MethodInfo[] calleds = new MethodInfo[] { combin, remove };
     MethodBuilder[] methods = new MethodBuilder[2];
     for (int i = 0; i < 2; i++)
     {
         methods[i] = type.DefineMethod(nameprefixes[i] + "__" + method.Name,
             MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Private,
             typeof(void), new Type[] { delegateType });
         ILGenerator gen = methods[i].GetILGenerator();
         gen.Emit(OpCodes.Ldarg_0);
         gen.Emit(OpCodes.Ldarg_0);
         gen.Emit(OpCodes.Ldfld, field);
         gen.Emit(OpCodes.Ldarg_1);
         gen.Emit(OpCodes.Call, calleds[i]);
         gen.Emit(OpCodes.Castclass, delegateType);
         gen.Emit(OpCodes.Stfld, field);
         gen.Emit(OpCodes.Ret);
     }
     e.SetAddOnMethod(methods[0]);
     e.SetRemoveOnMethod(methods[1]);
     return field;
 }