public void SetAddOnMethod_PInvokeImplMethod_Twice()
        {
            TypeBuilder   type         = Helpers.DynamicType(TypeAttributes.Abstract);
            EventBuilder  eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method       = type.DefineMethod("TestMethod", MethodAttributes.PinvokeImpl);

            eventBuilder.SetAddOnMethod(method);
            eventBuilder.SetAddOnMethod(method);
        }
예제 #2
0
        public void TestOnPInvokeMethod()
        {
            EventBuilder  ev     = TypeBuilder.DefineEvent("Event_PosTest4", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method = TypeBuilder.DefineMethod("Method_PosTest4", MethodAttributes.PinvokeImpl);

            ev.SetAddOnMethod(method);

            // add this method again
            ev.SetAddOnMethod(method);
        }
예제 #3
0
        public void TestOnAbstractMethod()
        {
            EventBuilder  ev     = TypeBuilder.DefineEvent("Event_PosTest1", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method = TypeBuilder.DefineMethod("Method_PosTest1", MethodAttributes.Abstract | MethodAttributes.Virtual);

            ev.SetAddOnMethod(method);

            // add this method again
            ev.SetAddOnMethod(method);
        }
        public void SetAddOnMethod_StaticMethod_Twice()
        {
            TypeBuilder   type         = Helpers.DynamicType(TypeAttributes.Abstract);
            EventBuilder  eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method       = type.DefineMethod("TestMethod", MethodAttributes.Static);
            ILGenerator   ilGenerator  = method.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ret);

            eventBuilder.SetAddOnMethod(method);
            eventBuilder.SetAddOnMethod(method);
        }
예제 #5
0
        public void TestOnStaticMethod()
        {
            byte[] bytes = new byte[MethodBodyLength];
            TestLibrary.Generator.GetBytes(bytes);
            EventBuilder  ev     = TypeBuilder.DefineEvent("Event_PosTest3", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method = TypeBuilder.DefineMethod("Method_PosTest3", MethodAttributes.Static);
            ILGenerator   ilgen  = method.GetILGenerator();

            ilgen.Emit(OpCodes.Ret);

            ev.SetAddOnMethod(method);

            // add this method again
            ev.SetAddOnMethod(method);
        }
        public void AddEventHandler_ComObjectWithMultipleComEventInterfaceAttribute_ThrowsAmbiguousMatchException()
        {
            // C# doesn't let us apply multiple ComEventInterface values, so RefEmit is necessary.
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("assembly"), AssemblyBuilderAccess.Run);
            ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule("module");
            TypeBuilder     typeBuilder     = moduleBuilder.DefineType("name", TypeAttributes.Interface | TypeAttributes.Abstract);

            typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(ComEventInterfaceAttribute).GetConstructors()[0], new object[] { typeof(int), typeof(string) }));
            typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(typeof(ComEventInterfaceAttribute).GetConstructors()[0], new object[] { typeof(string), typeof(string) }));

            MethodBuilder addMethod = typeBuilder.DefineMethod("add_Event", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Abstract, typeof(void), new Type[] { typeof(EventHandler) });

            addMethod.GetILGenerator().Emit(OpCodes.Ret);

            EventBuilder eventBuilder = typeBuilder.DefineEvent("Event", EventAttributes.None, typeof(EventHandler));

            eventBuilder.SetAddOnMethod(addMethod);

            var      attribute = new ComAwareEventInfo(typeBuilder.CreateType(), "Event");
            var      target    = new ComImportObject();
            Delegate handler   = new EventHandler(EventHandler);

            Assert.Throws <AmbiguousMatchException>(() => attribute.AddEventHandler(target, handler));
            Assert.Throws <AmbiguousMatchException>(() => attribute.RemoveEventHandler(target, handler));
        }
예제 #7
0
        /// <summary>
        /// Implements an interface event in a duck proxy type using a given type builder.
        /// If successful, the implemented event will be added to the given proxy member dictionary.
        /// </summary>
        /// <param name="proxyType">Type builder for the duck proxy type.</param>
        /// <param name="proxyMembers">Dictionary of members of the proxy type.</param>
        /// <param name="duckField">Field that holds a reference to the duck object to forward calls to.</param>
        /// <param name="interfaceEvent">The interface event to implement.</param>
        private void ImplementEvent(TypeBuilder proxyType, ProxyMemberDictionary proxyMembers, FieldInfo duckField, EventInfo interfaceEvent)
        {
            EventInfo duckEvent = FindDuckEvent(interfaceEvent);

            if (duckEvent == null)
            {
                throw new NotImplementedException("Duck type does not implement an event named \"" + interfaceEvent.Name + "\" with the same event handler type.");
            }

            EventBuilder proxyEvent = proxyType.DefineEvent(interfaceEvent.Name, EventAttributes.None, interfaceEvent.EventHandlerType);

            // Associated methods appear before the event in the member array; thus, they have already been
            // defined and implemented.  The proxy member dictionary is used to refer to these.
            proxyEvent.SetAddOnMethod((MethodBuilder)(proxyMembers[duckEvent.GetAddMethod()]));
            proxyEvent.SetRemoveOnMethod((MethodBuilder)(proxyMembers[duckEvent.GetRemoveMethod()]));
            proxyEvent.SetRaiseMethod((MethodBuilder)(proxyMembers[duckEvent.GetRaiseMethod()]));
            MethodInfo[] otherDuckMethods = duckEvent.GetOtherMethods();
            foreach (MethodInfo otherDuckMethod in otherDuckMethods)
            {
                if (proxyMembers.ContainsKey(otherDuckMethod))
                {
                    proxyEvent.AddOtherMethod((MethodBuilder)(proxyMembers[otherDuckMethod]));
                }
            }

            // Add proxy event to the proxy member dictionary
            // (This is not really necessary, but good to keep things consistent)
            // proxyMembers.Add(duckEvent, proxyEvent);
            // For some reason, EventBuilder does not inherit MemberInfo, so it cannot be added.
        }
예제 #8
0
        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);
        }
예제 #9
0
        public void TestDefineEvent()
        {
            AssemblyName myAsmName =
                new AssemblyName("TypeBuilderGetFieldTest");
            AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly(
                myAsmName, AssemblyBuilderAccess.Run);
            ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1");

            TypeBuilder myType = myModule.DefineType("Sample",
                                                     TypeAttributes.Class | TypeAttributes.Public);

            string[] typeParamNames = { "T" };
            GenericTypeParameterBuilder[] typeParams =
                myType.DefineGenericParameters(typeParamNames);

            EventBuilder  eb          = myType.DefineEvent("TestEvent", EventAttributes.None, typeof(int));
            MethodBuilder addOnMethod = myType.DefineMethod("addOnMethod", MethodAttributes.Public);
            ILGenerator   ilGen       = addOnMethod.GetILGenerator();

            ilGen.Emit(OpCodes.Ret);
            MethodBuilder removeOnMethod = myType.DefineMethod("removeOnMethod", MethodAttributes.Public);

            ilGen = removeOnMethod.GetILGenerator();
            ilGen.Emit(OpCodes.Ret);
            eb.SetAddOnMethod(addOnMethod);
            eb.SetRemoveOnMethod(removeOnMethod);

            Type t = myType.CreateTypeInfo().AsType();

            EventInfo ei = t.GetEvent("TestEvent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            Assert.NotNull(ei);
        }
예제 #10
0
        public void DefineEvent(string name, EventAttributes attributes, Type eventType, string expectedName, EventAttributes expectedAttributes)
        {
            TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public);

            type.DefineGenericParameters("T");

            EventBuilder  eventBuilder = type.DefineEvent(name, attributes, eventType);
            MethodBuilder addOnMethod  = type.DefineMethod("addOnMethod", MethodAttributes.Public);

            addOnMethod.GetILGenerator().Emit(OpCodes.Ret);

            MethodBuilder removeOnMethod = type.DefineMethod("removeOnMethod", MethodAttributes.Public);

            removeOnMethod.GetILGenerator().Emit(OpCodes.Ret);

            eventBuilder.SetAddOnMethod(addOnMethod);
            eventBuilder.SetRemoveOnMethod(removeOnMethod);

            Type createdType = type.CreateTypeInfo().AsType();

            Assert.Equal(type.AsType().GetEvents(Helpers.AllFlags), createdType.GetEvents(Helpers.AllFlags));
            Assert.Equal(type.AsType().GetEvent(expectedName, Helpers.AllFlags), createdType.GetEvent(expectedName, Helpers.AllFlags));

            EventInfo eventInfo = createdType.GetEvent(expectedName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            Assert.Equal(expectedName, eventInfo.Name);
            Assert.Equal(createdType, eventInfo.DeclaringType);
            Assert.Equal(expectedAttributes, eventInfo.Attributes);
            Assert.Equal((expectedAttributes & EventAttributes.SpecialName) != 0, eventInfo.IsSpecialName);
            Assert.Null(eventInfo.EventHandlerType);
        }
        public void SetAddOnMethod_NullMethod_ThrowsArgumentNullException()
        {
            TypeBuilder  type         = Helpers.DynamicType(TypeAttributes.Abstract);
            EventBuilder eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(TestEventHandler));

            AssertExtensions.Throws <ArgumentNullException>("mdBuilder", () => eventBuilder.SetAddOnMethod(null));
        }
예제 #12
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);
            }
예제 #13
0
        public EventBuilder CreateInterceptableEvent(EventDefinition eventDefinition)
        {
            if (eventDefinition is null)
            {
                throw new ArgumentNullException(nameof(eventDefinition));
            }

            var          attributes        = StaticReadOnlyFieldAttributes;
            FieldBuilder memberField       = DefineField(eventDefinition.MemberFieldName, typeof(EventInfo), attributes);
            FieldBuilder addMethodField    = DefineField(eventDefinition.AddMethodDefinition.CallerMethodFieldName, typeof(MethodInfo), attributes);
            FieldBuilder removeMethodField = DefineField(eventDefinition.RemoveMethodDefinition.CallerMethodFieldName, typeof(MethodInfo), attributes);

            EventBuilder eventBuilder = DefineEvent(eventDefinition.Name, eventDefinition.Attributes, eventDefinition.EventHandlerType);

            var           addMethodDefinition = eventDefinition.AddMethodDefinition;
            MethodBuilder addMethodBuilder    = interceptableMethodBuilder.CreateMethod(this, addMethodDefinition, eventDefinition.Event, memberField, addMethodField);

            AttributeHelper.AddInterceptorAttributes(addMethodBuilder, eventDefinition.AddOnInterceptorAttributes);
            eventBuilder.SetAddOnMethod(addMethodBuilder);

            var           removeMethodDefinition = eventDefinition.RemoveMethodDefinition;
            MethodBuilder removeMethodBuilder    = interceptableMethodBuilder.CreateMethod(this, removeMethodDefinition, eventDefinition.Event, memberField, removeMethodField);

            AttributeHelper.AddInterceptorAttributes(removeMethodBuilder, eventDefinition.RemoveOnInterceptorAttributes);
            eventBuilder.SetRemoveOnMethod(removeMethodBuilder);

            eventMappings.Add(new EventMapping(eventDefinition, eventBuilder, memberField, addMethodField, removeMethodField, addMethodBuilder, removeMethodBuilder));

            return(eventBuilder);
        }
예제 #14
0
        public EventBuilder DefineFullEvent(string eventName, EventAttributes eventAttributes, Type eventType, FieldBuilder field)
        {
            if (eventName is null)
            {
                throw new ArgumentNullException(nameof(eventName));
            }
            if (eventType is null)
            {
                throw new ArgumentNullException(nameof(eventType));
            }
            if (field is null)
            {
                throw new ArgumentNullException(nameof(field));
            }

            EventBuilder eventBuilder = DefineEvent(eventName, eventAttributes, eventType);

            MethodBuilder addMethodBuilder = typeBuilder.DefineAddMethod(eventName, eventType, field);

            eventBuilder.SetAddOnMethod(addMethodBuilder);
            methods.Add(addMethodBuilder);

            MethodBuilder removeMethodBuilder = typeBuilder.DefineRemoveMethod(eventName, eventType, field);

            eventBuilder.SetRemoveOnMethod(removeMethodBuilder);
            methods.Add(removeMethodBuilder);

            return(eventBuilder);
        }
예제 #15
0
        public static EventBuilder DefineFullEvent(this TypeBuilder typeBuilder, string eventName,
                                                   MethodAttributes methodAttributes, CallingConventions callingConvention, EventAttributes eventAttributes, Type eventType, FieldBuilder field)
        {
            if (typeBuilder is null)
            {
                throw new ArgumentNullException(nameof(typeBuilder));
            }
            if (eventName is null)
            {
                throw new ArgumentNullException(nameof(eventName));
            }
            if (eventType is null)
            {
                throw new ArgumentNullException(nameof(eventType));
            }
            if (field is null)
            {
                throw new ArgumentNullException(nameof(field));
            }

            EventBuilder eventBuilder = typeBuilder.DefineEvent(eventName, eventAttributes, eventType);

            MethodBuilder addMethodBuilder = DefineAddMethod(typeBuilder, eventName, methodAttributes, callingConvention, eventType, field);

            eventBuilder.SetAddOnMethod(addMethodBuilder);

            MethodBuilder removeMethodBuilder = DefineRemoveMethod(typeBuilder, eventName, methodAttributes, callingConvention, eventType, field);

            eventBuilder.SetRemoveOnMethod(removeMethodBuilder);

            return(eventBuilder);
        }
예제 #16
0
        public void DefineEvent_CalledMultipleTimes_Works()
        {
            TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public);

            for (int i = 0; i < 2; i++)
            {
                EventBuilder  eventBuilder = type.DefineEvent("EventName", EventAttributes.None, typeof(int));
                MethodBuilder addOnMethod  = type.DefineMethod("addOnMethod", MethodAttributes.Public);
                ILGenerator   ilGenerator  = addOnMethod.GetILGenerator();
                ilGenerator.Emit(OpCodes.Ret);

                MethodBuilder removeOnMethod = type.DefineMethod("removeOnMethod", MethodAttributes.Public);
                ilGenerator = removeOnMethod.GetILGenerator();
                ilGenerator.Emit(OpCodes.Ret);

                eventBuilder.SetAddOnMethod(addOnMethod);
                eventBuilder.SetRemoveOnMethod(removeOnMethod);
            }

            Type createdType = type.CreateTypeInfo().AsType();

            EventInfo[] events = createdType.GetEvents();
            Assert.Equal(1, events.Length);
            Assert.Equal("EventName", events[0].Name);
        }
        private void BuildEvent(DynamicType type, EventDefinition eventDefinition)
        {
            EventBuilder eventBuilder = type.DefineEvent(eventDefinition.Name,
                                                         (System.Reflection.EventAttributes)eventDefinition.Attributes,
                                                         ResolveType(eventDefinition.EventType));

            // TODO: Custom modifiers and other stuff.

            if (eventDefinition.InvokeMethod != null)
            {
                eventBuilder.SetRaiseMethod(BuildMethod(type, eventDefinition.InvokeMethod));
            }
            if (eventDefinition.AddMethod != null)
            {
                eventBuilder.SetAddOnMethod(BuildMethod(type, eventDefinition.AddMethod));
            }
            if (eventDefinition.RemoveMethod != null)
            {
                eventBuilder.SetRemoveOnMethod(BuildMethod(type, eventDefinition.RemoveMethod));
            }

            metadataPass.Add(delegate
            {
                InitializeCustomAttributes(eventBuilder.SetCustomAttribute, eventDefinition.CustomAttributes);
            });
        }
        public void SetAddOnMethod_MultipleDifferentMethods()
        {
            TypeBuilder   type         = Helpers.DynamicType(TypeAttributes.Abstract);
            EventBuilder  eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method1      = type.DefineMethod("PInvokeMethod", MethodAttributes.PinvokeImpl);
            MethodBuilder method2      = type.DefineMethod("InstanceMethod", MethodAttributes.Public);
            ILGenerator   ilGenerator  = method2.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ret);
            MethodBuilder method3 = type.DefineMethod("StaticMethod", MethodAttributes.Static);
            MethodBuilder method4 = type.DefineMethod("AbstractMethod", MethodAttributes.Abstract | MethodAttributes.Virtual);

            eventBuilder.SetAddOnMethod(method1);
            eventBuilder.SetAddOnMethod(method2);
            eventBuilder.SetAddOnMethod(method3);
            eventBuilder.SetAddOnMethod(method4);
        }
예제 #19
0
        public void TestThrowsExceptionOnCreateTypeCalled()
        {
            EventBuilder  ev     = TypeBuilder.DefineEvent("Event_NegTest2", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method = TypeBuilder.DefineMethod("Method_NegTest2", MethodAttributes.Abstract | MethodAttributes.Virtual);

            TypeBuilder.CreateTypeInfo().AsType();

            Assert.Throws <InvalidOperationException>(() => { ev.SetAddOnMethod(method); });
        }
        public void SetAddOnMethod_TypeCreated_ThrowsInvalidOperationException()
        {
            TypeBuilder   type         = Helpers.DynamicType(TypeAttributes.Abstract);
            EventBuilder  eventBuilder = type.DefineEvent("TestEvent", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method       = type.DefineMethod("TestMethod", MethodAttributes.Abstract | MethodAttributes.Virtual);

            type.CreateTypeInfo().AsType();

            Assert.Throws <InvalidOperationException>(() => eventBuilder.SetAddOnMethod(method));
        }
예제 #21
0
        static void AddEvent(TypeBuilder typeBuilder, EventInfo duckEvent, EventInfo evt)
        {
            EventBuilder evtBuilder = typeBuilder.DefineEvent(evt.Name, EventAttributes.None, evt.EventHandlerType);
            var          addMethod  = AddMethod(typeBuilder, duckEvent.GetAddMethod(), evt.GetAddMethod());

            evtBuilder.SetAddOnMethod(addMethod);
            var removeMethod = AddMethod(typeBuilder, duckEvent.GetRemoveMethod(), evt.GetRemoveMethod());

            evtBuilder.SetRemoveOnMethod(removeMethod);
        }
예제 #22
0
        //create add remove method from http://grahammurray.wordpress.com/tag/reflection-emit/
        FieldBuilder CreatePropertyChangedEvent(TypeBuilder type)
        {
            FieldBuilder eventField   = type.DefineField("PropertyChanged", typeof(PropertyChangedEventHandler), FieldAttributes.Private);
            EventBuilder eventBuilder = type.DefineEvent("PropertyChanged", EventAttributes.None, typeof(PropertyChangedEventHandler));

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

            return(eventField);
        }
예제 #23
0
        public void TestOnMultipleDifferentMethods()
        {
            byte[] bytes = new byte[MethodBodyLength];
            TestLibrary.Generator.GetBytes(bytes);

            EventBuilder  ev      = TypeBuilder.DefineEvent("Event_PosTest5", EventAttributes.None, typeof(TestEventHandler));
            MethodBuilder method1 = TypeBuilder.DefineMethod("PMethod_PosTest5", MethodAttributes.PinvokeImpl);
            MethodBuilder method2 = TypeBuilder.DefineMethod("IMethod_PosTest5", MethodAttributes.Public);
            ILGenerator   ilgen   = method2.GetILGenerator();

            ilgen.Emit(OpCodes.Ret);
            MethodBuilder method3 = TypeBuilder.DefineMethod("SMethod_PosTest5", MethodAttributes.Static);
            MethodBuilder method4 = TypeBuilder.DefineMethod("AMethod_PosTest5", MethodAttributes.Abstract | MethodAttributes.Virtual);

            ev.SetAddOnMethod(method1);
            ev.SetAddOnMethod(method2);
            ev.SetAddOnMethod(method3);
            ev.SetAddOnMethod(method4);
        }
예제 #24
0
        public static void Invoke_Event_Add_And_Remove_And_Raise_Invokes_Correct_Methods()
        {
            // C# cannot emit raise_Xxx method for the event, so we must use System.Reflection.Emit to generate such event.
            AssemblyBuilder ab   = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("EventBuilder"), AssemblyBuilderAccess.Run);
            ModuleBuilder   modb = ab.DefineDynamicModule("mod");
            TypeBuilder     tb   = modb.DefineType("TestType_IEventService", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract);
            EventBuilder    eb   = tb.DefineEvent("AddRemoveRaise", EventAttributes.None, typeof(EventHandler));

            eb.SetAddOnMethod(tb.DefineMethod("add_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) }));
            eb.SetRemoveOnMethod(tb.DefineMethod("remove_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) }));
            eb.SetRaiseMethod(tb.DefineMethod("raise_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventArgs) }));
            TypeInfo ieventServiceTypeInfo = tb.CreateTypeInfo();

            List <MethodInfo> invokedMethods = new List <MethodInfo>();
            object            proxy          =
                typeof(DispatchProxy)
                .GetRuntimeMethod("Create", Array.Empty <Type>()).MakeGenericMethod(ieventServiceTypeInfo.AsType(), typeof(TestDispatchProxy))
                .Invoke(null, null);

            ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
            {
                invokedMethods.Add(method);
                return(null);
            };

            EventHandler handler = new EventHandler((sender, e) => {});

            proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "add_AddRemoveRaise").Invoke(proxy, new object[] { handler });
            proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "raise_AddRemoveRaise").Invoke(proxy, new object[] { EventArgs.Empty });
            proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "remove_AddRemoveRaise").Invoke(proxy, new object[] { handler });

            Assert.True(invokedMethods.Count == 3, String.Format("Expected 3 method invocations but received {0}", invokedMethods.Count));

            EventInfo eventInfo = ieventServiceTypeInfo.GetDeclaredEvent("AddRemoveRaise");

            Assert.NotNull(eventInfo);

            MethodInfo expectedMethod = eventInfo.AddMethod;

            Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[0]));

            expectedMethod = eventInfo.RaiseMethod;
            Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[1]));

            expectedMethod = eventInfo.RemoveMethod;
            Assert.True(invokedMethods[2] != null && expectedMethod == invokedMethods[2], String.Format("Third invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[1]));
        }
        public void Generate()
        {
            if (m_addOnMethod != null)
            {
                m_addOnMethod.Generate();
                m_builder.SetAddOnMethod(m_addOnMethod.MethodBuilder);
            }

            if (m_removeOnMethod != null)
            {
                m_removeOnMethod.Generate();
                m_builder.SetRemoveOnMethod(m_removeOnMethod.MethodBuilder);
            }
        }
예제 #26
0
        private void AddEventDefinition(EventInfo @event, MethodBuilder addMethod, MethodBuilder removeMethod)
        {
            EventBuilder newEvent = this.typeBuilder.DefineEvent(@event.Name, @event.Attributes, @event.EventHandlerType);

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

            if (removeMethod != null)
            {
                newEvent.SetRemoveOnMethod(removeMethod);
            }
        }
예제 #27
0
        /// <summary>
        /// Adds the property and its accessor methods to the type builder.
        /// </summary>
        internal void AddToTypeBuilder()
        {
            Debug.Assert(IsFrozen);

            if (mEventBuilder == null)
            {
                mAddAccessorMethod.AddToTypeBuilder();
                mRemoveAccessorMethod.AddToTypeBuilder();
                mRaiserMethod.AddToTypeBuilder();

                mEventBuilder = Engine.TypeBuilder.DefineEvent(mName, EventAttributes.None, mType);
                mEventBuilder.SetAddOnMethod(mAddAccessorMethod.MethodBuilder);
                mEventBuilder.SetRemoveOnMethod(mRemoveAccessorMethod.MethodBuilder);
            }
        }
예제 #28
0
        public static void GenHookupEvent(TypeBuilder typeB, EventInfo declEvent, string @interface, HashSet <MethodInfo> evaluating)
        {
            EventBuilder event_builder = typeB.DefineEvent(declEvent.Name,
                                                           declEvent.Attributes,
                                                           declEvent.EventHandlerType);

            MethodInfo[] sources = new MethodInfo[] { declEvent.GetAddMethod(),
                         declEvent.GetRemoveMethod() };

            foreach (MethodInfo source in sources)
            {
                if (null == source)
                {
                    continue;
                }

                evaluating.Remove(source);

                MethodBuilder meth_builder = CreateMethodBuilder(typeB, source);
                ILGenerator   ilg          = meth_builder.GetILGenerator();

                bool adding = sources[0] == source;

                EmitThis(ilg);

                //interface
                ilg.Emit(OpCodes.Ldstr, @interface);

                ilg.Emit(OpCodes.Ldstr, declEvent.Name);

                ilg.Emit(OpCodes.Ldarg_1);

                ilg.Emit(OpCodes.Ldc_I4, adding ? 1 : 0);

                ilg.Emit(OpCodes.Tailcall);
                ilg.Emit(toggleSignalMethod.IsFinal ? OpCodes.Call : OpCodes.Callvirt, toggleSignalMethod);
                ilg.Emit(OpCodes.Ret);

                if (adding)
                {
                    event_builder.SetAddOnMethod(meth_builder);
                }
                else
                {
                    event_builder.SetRemoveOnMethod(meth_builder);
                }
            }
        }
예제 #29
0
        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);
        }
예제 #30
0
        public void Generate()
        {
            if (addMethod == null)
            {
                throw new InvalidOperationException("Event add method was not created");
            }
            if (removeMethod == null)
            {
                throw new InvalidOperationException("Event remove method was not created");
            }
            addMethod.Generate();
            eventBuilder.SetAddOnMethod(addMethod.MethodBuilder);

            removeMethod.Generate();
            eventBuilder.SetRemoveOnMethod(removeMethod.MethodBuilder);
        }
예제 #31
0
		public override bool Define ()
		{
			if (!base.Define ())
				return false;

			if (!MemberType.IsDelegate) {
				Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
			}

			if (!CheckBase ())
				return false;

			//
			// Now define the accessors
			//
			var AddBuilder = Add.Define (Parent);
			if (AddBuilder == null)
				return false;

			var RemoveBuilder = remove.Define (Parent);
			if (RemoveBuilder == null)
				return false;

			EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
			EventBuilder.SetAddOnMethod (AddBuilder);
			EventBuilder.SetRemoveOnMethod (RemoveBuilder);

			spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);

			Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
			Parent.MemberCache.AddMember (this, AddBuilder.Name, Add.Spec);
			Parent.MemberCache.AddMember (this, RemoveBuilder.Name, remove.Spec);

			return true;
		}