Пример #1
0
    public static bool Contains(this System.Delegate del, System.Type type, string methodName)
    {
        bool contains = false;

        if (del != null && del.GetInvocationList() != null)
        {
            contains = !System.Array.TrueForAll(del.GetInvocationList(), invoker => invoker.Method.DeclaringType != type && invoker.Method.Name != methodName);
        }
        return(contains);
    }
        static internal void ExecuteAndSendResult(Binder binder, System.Delegate callback, object[] arguments, double id, bool execute, bool isDynamic)
        {
            object result = null;

            if (execute)
            {
                if (!isDynamic)
                {
                    foreach (var invocation in callback.GetInvocationList())
                    {
                        result = invocation.Method.Invoke(invocation.Target, arguments);
                    }
                }
                else
                {
                    result = callback.DynamicInvoke(arguments);
                }
                if (result != null && id != 0)
                {
                    binder.Return(id, result);
                }
            }
            else
            {
                binder.SendError();
            }
        }
Пример #3
0
 // Token: 0x06001860 RID: 6240
 // RVA: 0x00014E5C File Offset: 0x0001305C
 private static void ValidateCallback(Delegate delegate_0)
 {
     if (delegate_0 != null && delegate_0.GetInvocationList().Length > 1)
     {
         throw new NotSupportedException("SmartThreadPool doesn't support delegates chains");
     }
 }
Пример #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="event"></param>
        internal static void OnEvent(object sender, EventArgs e, System.Delegate @event)
        {
            bool eventFired = false;

            if (@event != null)
            {
                foreach (System.Delegate singleCast in @event.GetInvocationList())
                {
                    eventFired = false;
                    try {
                        ISynchronizeInvoke syncInvoke = (ISynchronizeInvoke)singleCast.Target;
                        if (syncInvoke != null && syncInvoke.InvokeRequired)
                        {
                            eventFired = true;
                            syncInvoke.BeginInvoke(singleCast, new object[] { sender, e });
                        }
                        else
                        {
                            eventFired = true;
                            singleCast.DynamicInvoke(new object[] { sender, e });
                        }
                    }
                    catch (System.Reflection.TargetInvocationException ex) {
                        if (!eventFired)
                        {
                            singleCast.DynamicInvoke(new object[] { sender, e });
                        }
                        Debug.Print("OnEvent: " + ex.InnerException.Message);
                    }
                }
            }
        }
Пример #5
0
        public void Dump(MainLoopEvent mainloopevent)
        {
#if UNITY_EDITOR
            var en = this.callbackMap.GetEnumerator();
            while (en.MoveNext())
            {
                Action <object, int> act = en.Current.Value;
                if (act != null && callbackListMap[en.Current.Key].Count > 0)
                {
                    System.Delegate d         = act as System.Delegate;
                    Delegate[]      delegates = d.GetInvocationList();
                    for (int i = 0; i < delegates.Length; ++i)
                    {
                        LogMgr.LogWarningFormat(" InstanceCacheDelegate {0} in {1} not clear at {2}", delegates[i].Method.Name, delegates[i].Method.DeclaringType, mainloopevent);
                    }
                }
            }

            var listen = this.callbackListMap.GetEnumerator();
            while (listen.MoveNext())
            {
                List <object> list = listen.Current.Value;
                if (list != null && list.Count > 0)
                {
                    for (int i = 0; i < list.Count; ++i)
                    {
                        object o = list[i];
                        LogMgr.LogWarningFormat("InstanceCacheDelegate {0} not clear at {1}", o, mainloopevent);
                    }
                }
            }
#endif
        }
Пример #6
0
        /// <summary>
        /// Invokes a method delegate asynchrounously and thread safe.
        /// </summary>
        /// <param name="method">The delegate method to invoke</param>
        /// <param name="args">The arguments passed to the delegate.</param>
        public static void Invoke(Delegate method, object[] args)
        {
            if (method != null)
            {
                foreach (Delegate handler in method.GetInvocationList())
                {
                    if (handler.Target is Control)
                    {
                        Control target = handler.Target as Control;

                        if (target.IsHandleCreated)
                        {
                            target.BeginInvoke(handler, args);
                        }
                    }
                    else if (handler.Target is ISynchronizeInvoke)
                    {
                        ISynchronizeInvoke target = handler.Target as ISynchronizeInvoke;
                        target.BeginInvoke(handler, args);
                    }
                    else
                    {
                        handler.DynamicInvoke(args);
                    }
                }
            }
        }
Пример #7
0
        private static void AddTaskDelay(Delegate ev, object[] paramArray, int time)
        {
            System.Threading.Thread.Sleep(time);
            bool bFired;

            if (ev != null)
            {
                foreach (Delegate singleCast in ev.GetInvocationList())
                {
                    bFired = false;
                    try
                    {
                        ISynchronizeInvoke syncInvoke = (ISynchronizeInvoke)singleCast.Target;
                        if (syncInvoke != null && syncInvoke.InvokeRequired)
                        {
                            bFired = true;
                            syncInvoke.BeginInvoke(singleCast, paramArray);
                        }
                        else
                        {
                            bFired = true;
                            singleCast.DynamicInvoke(paramArray);
                        }
                    }
                    catch (Exception)
                    {
                        if (!bFired)
                            singleCast.DynamicInvoke(paramArray);
                    }
                }
            }
        }
Пример #8
0
    public static void DispatchEvent(object source, string eventName, EventArgs eventArgs)
    {
        EventInfo eventObject = source.GetType().GetEvent(eventName);


        if (eventObject != null)
        {
            IEnumerable <FieldInfo> fis = source.GetType().GetRuntimeFields();
            foreach (FieldInfo fi in fis)
            {
                if (fi.Name == eventName + "Event")
                {
                    System.Delegate del = fi.GetValue(source) as System.Delegate;

                    List <System.Delegate> invocationList = del.GetInvocationList().ToList();


                    foreach (System.Delegate invItem in invocationList)
                    {
                        invItem.DynamicInvoke(source, eventArgs);
                    }
                }
            }
        }
    }
Пример #9
0
 static void DisplayDelegateInfo(Delegate delObj)
 {
     foreach (Delegate d in delObj.GetInvocationList())
     {
         Console.WriteLine("Method name: {0}", d.Method);
         Console.WriteLine("Type name: {0}", d.Target);
     }
 }
Пример #10
0
 private void ReadDelegate( Delegate delObj )
 {
     foreach (Delegate del in delObj.GetInvocationList())
      {
     Console.WriteLine("Method {0}", del.Method);
     Console.WriteLine("Target {0}", del.Target);
      }
 }
Пример #11
0
 public static void DisplayDelegateInfo(Delegate del)
 {
     foreach (var item in del.GetInvocationList())
     {
         Console.WriteLine("Method Name {0}", del.Method);
         Console.WriteLine("Type Name {0}", del.Target);
     }
 }
Пример #12
0
        public static Delegate[] GetDelegateList(Delegate del)
        {
            if(del == null) {
                throw new ArgumentNullException("del");
            }

            return del.GetInvocationList();
        }
Пример #13
0
 static void DisplayDelegateInfo(Delegate delObj)
 {
     //print the names of each member in the delegates invocation list
     foreach (Delegate d in delObj.GetInvocationList())
     {
         Console.WriteLine("Method Name: {0}", d.Method);
         Console.WriteLine("Type Name: {0}", d.Target);
     }
 }
 public static void GetDelegateDetails(Delegate d)
 {
     foreach (Delegate dg in d.GetInvocationList())
     {
         Console.WriteLine("Type is {0}",dg.GetType());
         Console.WriteLine("Method is {0}",dg.Method);
         Console.WriteLine("target is {0}",dg.Target);
     }
 }
Пример #15
0
 private static void Handle(Delegate del, PacketHandlerEventArgs args, params object[] parameters)
 {
     if (del != null)
         foreach (Delegate d in del.GetInvocationList())
         {
             bool? result = (bool?)d.Method.Invoke(d.Target, parameters);
             if (result.HasValue)
                 args.Block = result.Value;
         }
 }
Пример #16
0
        public int CountTotalEmployee()
        {
            int total = 0;

            foreach (System.Delegate i in allDelegates.GetInvocationList())
            {
                total += (int)i.DynamicInvoke();
            }
            return(total);
        }
Пример #17
0
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="d">The delegate the info object should be created for.</param>
		public DelegateMetadata(Delegate d)
		{
			Requires.NotNull(d, nameof(d));

			_delegate = d;
			_delegateType = d.GetType();

			var list = d.GetInvocationList();
			_targets = list.Select(info => info.Target).ToArray();
			_methods = list.Select(info => info.Method).ToArray();
		}
Пример #18
0
        public int CountTotalEmployees()
        {
            int totalEmployees = 0;

            foreach (System.Delegate calculate in allDelegate.GetInvocationList())
            {
                totalEmployees += (int)calculate.DynamicInvoke();
            }

            return(totalEmployees);
        }
        private static dynamic Cast(Delegate source, Type type)
        {
            Delegate[] delegates = source.GetInvocationList();
            if (delegates.Length == 1)
                return Delegate.CreateDelegate(type,
                    delegates[0].Target, delegates[0].Method);

            Delegate[] delegatesDest = new Delegate[delegates.Length];
            for (int nDelegate = 0; nDelegate < delegates.Length; nDelegate++)
                delegatesDest[nDelegate] = Delegate.CreateDelegate(type,
                    delegates[nDelegate].Target, delegates[nDelegate].Method);
            return Delegate.Combine(delegatesDest);
        }
Пример #20
0
 static public int GetInvocationList(IntPtr l)
 {
     try {
         System.Delegate self = (System.Delegate)checkSelf(l);
         var             ret  = self.GetInvocationList();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #21
0
    //////// - Nguyễn Việt Dũng : Anh em chú ý nhé. (BỎ COMMENT RA KHI MUỐN BIẾT SỰ KIỆN PHÁT SINH TỪ ĐÂU) - ////////////
    string LogEvent(System.Delegate _event)
    {
        if (_event == null)
        {
            return("");
        }
        string strDebug = "Event: " + _event.ToString() + " ->\n";

        foreach (System.Delegate _delegate in _event.GetInvocationList())
        {
            strDebug += "" + _delegate.Method.ReflectedType.Name + " : " + _delegate.Method.Name + "\n";
        }
        return(strDebug);
    }
Пример #22
0
 /// <summary>
 /// Invokes every delegate method in new thread (except synchronized handlers).
 /// </summary>
 /// <param name="handler"></param>
 /// <param name="parameters"></param>
 public static void InvokeAsync(Delegate handler, params object[] parameters)
 {
     if (handler != null) {
         foreach (Delegate d in handler.GetInvocationList()) {
             ISynchronizeInvoke sync = d.Target as ISynchronizeInvoke;
             if (sync != null) {
                 sync.BeginInvoke(d, parameters);
             }
             else {
                 ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncInvokeProc), new AsyncInvokeArgs(d.Method, d.Target, parameters));
             }
         }
     }
 }
Пример #23
0
 public static void RaiseEventOnUIThread(Delegate theEvent, object[] args)
 {
     foreach (Delegate d in theEvent.GetInvocationList())
     {
         ISynchronizeInvoke syncer = d.Target as ISynchronizeInvoke;
         if (syncer == null)
         {
             d.DynamicInvoke(args);
         }
         else
         {
             syncer.BeginInvoke(d, args);  // cleanup omitted
         }
     }
 }
Пример #24
0
 static int GetInvocationList(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.Delegate   obj = (System.Delegate)ToLua.CheckObject <System.Delegate>(L, 1);
         System.Delegate[] o   = obj.GetInvocationList();
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Пример #25
0
        public static MethodInfo[] GetMethodList(Delegate del)
        {
            if(del == null) {
                throw new ArgumentNullException("del");
            }

            Delegate[] delegates = del.GetInvocationList();
            MethodInfo[] methods = new MethodInfo[delegates.Length];

            for(int i = 0; i < delegates.Length; i++) {
                methods[i] = delegates[i].Method;
            }

            return methods;
        }
Пример #26
0
        public static void Invoke(Delegate handler, params object[] parameters)
        {
            if (handler != null) {
                foreach (Delegate d in handler.GetInvocationList()) {
                    ISynchronizeInvoke sync = d.Target as ISynchronizeInvoke;

                    if (sync != null && sync.InvokeRequired) {
                        // I need to call this asynchrounously because it caused deadlocks
                        sync.BeginInvoke(d, parameters);
                    }
                    else {
                        d.Method.Invoke(d.Target, parameters);
                    }
                }
            }
        }
Пример #27
0
        public static void CallAsyncMethod(Delegate eventDelegate, params object[] args)
        {
            if (eventDelegate != null)
            {
                Delegate[] delegates = eventDelegate.GetInvocationList();

                AsyncInvokeDelegate invoker = new AsyncInvokeDelegate(InvokeDelegate);

                AsyncCallback cleanUp = new AsyncCallback(AsyncDelegateCleanup);

                foreach (Delegate sink in delegates)
                {
                    invoker.BeginInvoke(sink, args, cleanUp, null);
                }
            }
        }
Пример #28
0
        public static void InvokeDelegateAsync(Delegate del, params object[] args)
        {
            if (del == null)
            { return; }

            AsyncCallback cleanUp = delegate(IAsyncResult asyncResult)
            {
                asyncResult.AsyncWaitHandle.Close();
            };

            AsyncFire asyncFire = new AsyncFire(InvokeDelegate);

            foreach (Delegate sink in del.GetInvocationList())
            {
                asyncFire.BeginInvoke(sink, args, cleanUp, null);
            }
        }
Пример #29
0
        public static bool IsDelegateSubscribers(Delegate _delegate)
        {
            bool result = false;
            if (_delegate != null)
            {
                lock (_delegate)
                {
                    if (_delegate != null)
                    {
                        Delegate[] list = _delegate.GetInvocationList();
                        result = ((list != null) && (list.Length != 0));
                    }
                }
            }

            return result;
        }
Пример #30
0
 static void DelegateReport(System.Delegate d, string name)
 {
   if (d == null) return;
   IFormatProvider fp = System.Globalization.CultureInfo.InvariantCulture;
   string title = string.Format(fp, "{0} Event\n", name);
   UnsafeNativeMethods.CRhinoEventWatcher_LogState(title);
   Delegate[] list = d.GetInvocationList();
   if (list != null && list.Length > 0)
   {
     for (int i = 0; i < list.Length; i++)
     {
       Delegate subD = list[i];
       Type t = subD.Target.GetType();
       string msg = string.Format(fp, "- Plug-In = {0}\n", t.Assembly.GetName().Name);
       UnsafeNativeMethods.CRhinoEventWatcher_LogState(msg);
     }
   }
 }
Пример #31
0
    static int GetInvocationList(IntPtr L)
    {
        ToLua.CheckArgsCount(L, 1);
        System.Delegate   obj = (System.Delegate)ToLua.CheckObject(L, 1, typeof(System.Delegate));
        System.Delegate[] o   = null;

        try
        {
            o = obj.GetInvocationList();
        }
        catch (Exception e)
        {
            return(LuaDLL.luaL_error(L, e.Message));
        }

        ToLua.Push(L, o);
        return(1);
    }
 public static void CallSafe(Delegate e, params object[] param)
 {
     try
     {
         foreach (Delegate d in e.GetInvocationList())
         {
             ISynchronizeInvoke syncer = d.Target as ISynchronizeInvoke;
             if (syncer == null)
             {
                 d.DynamicInvoke(param);
             }
             else
             {
                 syncer.BeginInvoke(d, param);
             }
         }
     }
     catch { }
 }
Пример #33
0
        public void Dump(MainLoopEvent mainloopevent)
        {
#if UNITY_EDITOR
            var en = this.cachesMap.GetEnumerator();
            while (en.MoveNext())
            {
                Action <int> act = en.Current.Value;
                if (act != null)
                {
                    System.Delegate d         = act as System.Delegate;
                    Delegate[]      delegates = d.GetInvocationList();
                    for (int i = 0; i < delegates.Length; ++i)
                    {
                        LogMgr.LogWarningFormat(" StaticDelegate {0} in {1} not clear at:{2}", delegates[i].Method.Name, delegates[i].Method.DeclaringType, mainloopevent);
                    }
                }
            }
#endif
        }
Пример #34
0
        /// <summary>
        /// Invokes all nonsynchronized handlers on new thread (all on one).
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="parameters"></param>
        public static void BeginInvoke(Delegate handler, params object[] parameters)
        {
            if (handler != null) {
                List<Delegate> list = new List<Delegate>();

                foreach (Delegate d in handler.GetInvocationList()) {
                    ISynchronizeInvoke sync = d.Target as ISynchronizeInvoke;
                    if (sync != null) {
                        sync.BeginInvoke(d, parameters);
                    }
                    else {
                        list.Add(d);
                    }
                }

                if (list.Count > 0) {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncInvokeListProc), new AsyncInvokeArgs(list, parameters));
                }
            }
        }
Пример #35
0
		/// <summary>
		/// Helper method for raising events safely.
		/// </summary>
		/// <param name="del">Delegate to invoke.</param>
		/// <param name="sender">The sender of the event.</param>
		/// <param name="e">The <see cref="EventArgs"/>.</param>
		/// <remarks>
		/// Use this method to invoke user code via delegates.
		/// This method will log any exceptions thrown in user code and immediately rethrow it.
		/// The typical usage is shown below.
		/// </remarks>
		/// <example>
		/// <code>
		/// [C#]
		/// public class PresentationImage
		/// {
		///    private event EventHandler _imageDrawingEvent;
		///    
		///    public void Draw()
		///    {
		///       EventsHelper.Fire(_imageDrawingEvent, this, new DrawImageEventArgs());
		///    }
		/// }
		/// </code>
		/// </example>
		public static void Fire(Delegate del, object sender, EventArgs e)
		{
			if (del == null)
				return;

			Delegate[] delegates = del.GetInvocationList();

			foreach(Delegate sink in delegates)
			{
				try
				{
					sink.DynamicInvoke(sender, e);
				}
				catch (Exception ex)
				{
                    Platform.Log(LogLevel.Error, ex);
					throw;
				}
			}
		}
Пример #36
0
 public static Thread raiseRegistedCallbacks(Delegate delegatesToInvoke, object[] parameters)
 {
     return O2Kernel_O2Thread.mtaThread(() =>
                                                {
                                                    if (delegatesToInvoke != null)
                                                        foreach (
                                                            Delegate registerCallback in
                                                                delegatesToInvoke.GetInvocationList())
                                                            try
                                                            {
                                                                registerCallback.DynamicInvoke(parameters);
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                log.error(
                                                                    "in raiseRegistedCallbacks, while invoking {0} : ",
                                                                    registerCallback.Method.Name,
                                                                    ex.Message);
                                                            }
                                                });
 }
Пример #37
0
    /// <summary>
    /// Indicates if a method with name, methodName is subscribed to a delegate, del, on object, invokingObject
    /// </summary>
    public static bool isSubscribed(this System.Delegate del, object invokingObject, string methodName)
    {
        bool isSubscribed = false;

        if (del != null) //Delegate has methods subscribed
        {
            System.Delegate[] invocationList = del.GetInvocationList();
            int i = 0;
            while (i < invocationList.Length && !isSubscribed)
            {
                System.Delegate subscribedDelegate = invocationList[i];
                if (del.Method.Name == methodName && subscribedDelegate.Target.Equals(invokingObject))
                {
                    isSubscribed = true;
                }

                i++;
            }
        }

        return(isSubscribed);
    }
Пример #38
0
        // From http://code.logos.com/blog/2008/07/casting_delegates.html
        public static System.Delegate Cast(this System.Delegate source, Type type)
        {
            if (source == null)
            {
                return(null);
            }

            System.Delegate[] delegates = source.GetInvocationList();
            if (delegates.Length == 1)
            {
                return(System.Delegate.CreateDelegate(type,
                                                      delegates[0].Target, delegates[0].Method));
            }

            System.Delegate[] delegatesDest = new System.Delegate[delegates.Length];
            for (int nDelegate = 0; nDelegate < delegates.Length; nDelegate++)
            {
                delegatesDest[nDelegate] = System.Delegate.CreateDelegate(type,
                                                                          delegates[nDelegate].Target, delegates[nDelegate].Method);
            }
            return(System.Delegate.Combine(delegatesDest));
        }
Пример #39
0
		/// <summary>
		/// Helper method for raising events safely.
		/// </summary>
		/// <param name="del">Delegate to invoke.</param>
		/// <param name="sender">The sender of the event.</param>
		/// <param name="e">The <see cref="EventArgs"/>.</param>
		/// <remarks>
		/// Use this method to invoke user code via delegates.
		/// This method will log any exceptions thrown in user code and immediately rethrow it.
		/// The typical usage is shown below.
		/// </remarks>
		/// <example>
		/// <code>
		/// [C#]
		/// public class PresentationImage
		/// {
		///    private event EventHandler _imageDrawingEvent;
		///    
		///    public void Draw()
		///    {
		///       EventsHelper.Fire(_imageDrawingEvent, this, new DrawImageEventArgs());
		///    }
		/// }
		/// </code>
		/// </example>
		public static void Fire(Delegate del, object sender, EventArgs e)
		{
			// TODO CR (Apr 13): del should really be EventHandler (and an overload added for EventHandler<T>) since this method won't work with any other kind of delegate
			//                   and a strongly typed API would help programmers from putting in the wrong arguments
			if (del == null)
				return;

			var delegates = del.GetInvocationList();

			foreach (var sink in delegates)
			{
				try
				{
					sink.DynamicInvoke(sender, e);
				}
				catch (Exception ex)
				{
					Platform.Log(LogLevel.Error, ex);
					throw;
				}
			}
		}
Пример #40
0
 public static object FireEvent(Delegate eventDelegate, params object[] paramValues)
 {
     if (eventDelegate == null) return null;
     if (eventDelegate is MulticastDelegate)
     {
         Delegate[] delegates = eventDelegate.GetInvocationList();
         if (delegates.Length > 1)
         {
             foreach (Delegate eventSink in delegates)
             {
                 FireEvent(eventSink, paramValues);
             }
             return null;
         }
         else
         {
             return FireSingleEvent(eventDelegate, paramValues);
         }
     }else
     {
         return FireSingleEvent(eventDelegate, paramValues);
     }
 }
Пример #41
0
        public static void TraceMethodAndDelegate(object sender, System.Delegate eventHandler)
        {
            if (!_enabled)
            {
                return;
            }

            try
            {
                StackFrame f             = new StackFrame(1);
                Delegate[] eventHandlers = (eventHandler != null ? eventHandler.GetInvocationList() : new Delegate[] {});

                // string target = (eventHandler != null ? eventHandlers[0].Target.GetType().Name : <

                string message = string.Format("{0}.{1} called, preparing to call {3} delegates.", f.GetMethod().DeclaringType.Name, f.GetMethod().Name, DateTime.Now.ToLongTimeString(), eventHandlers.Length.ToString());
                System.Diagnostics.Trace.WriteLine(message);

                //	eventHandler.Target.GetType().Name
            }
            catch (System.Exception systemException)
            {
                System.Diagnostics.Trace.WriteLine(systemException);
            }
        }
Пример #42
0
        /// <summary>
        /// Fires the specified event on the correct thread and passes
        /// in the specified arguments.
        /// </summary>
        /// <param name="eventToFire">The event to fire.</param>
        /// <param name="args">The arguments to pass to the event.</param>
        private static void fireEvent(Delegate eventToFire, params object[] args)
        {
            if (eventToFire == null)
                return;

            foreach (Delegate d in eventToFire.GetInvocationList())
            {
                ISynchronizeInvoke target = d.Target as ISynchronizeInvoke;

                if (target != null && target.InvokeRequired)
                {
                    target.Invoke(d, args);
                }
                else
                {
                    d.DynamicInvoke(args);
                }
            }
        }
Пример #43
0
        /// <summary>
        /// Removes non-public method targets from a delegate so that they
        /// can be safely serialized.
        /// </summary>
        /// <param name="d">The multicast or singlecast delegate to process</param>
        /// <returns>A delegate with only the public methods or null if all methods are non-public</returns>
        public static Delegate MakeSerializable(Delegate d)
        {
            if (d == null)
                return null;

            Delegate[] children = d.GetInvocationList();

            if (children.Length == 0)
                return null;
            else if (children.Length == 1 && d == children[0])
            {
                // Non-combined delegate
                if (d.Method.IsPublic)
                    return d;
                else
                    return null;
            }
            else
            {
                ArrayList publicChildren = new ArrayList(children.Length);

                foreach (Delegate child in children)
                {
                    Delegate publicChild = MakeSerializable(child);

                    if (publicChild != null)
                        publicChildren.Add(publicChild);
                }

                if (publicChildren.Count == 0)
                    return null;
                else if (publicChildren.Count == 1)
                    return (Delegate)publicChildren[0];
                else
                {
                    Delegate[] publicChildrenArray = new Delegate[publicChildren.Count];
                    for (int i = 0; i < publicChildren.Count; ++i)
                        publicChildrenArray[i] = (Delegate)publicChildren[i];

                    return Delegate.Combine(publicChildrenArray);
                }
            }
        }
Пример #44
0
        /// <summary>
        /// This method is used to actually fire an event
        /// 
        /// It returns true if it called any delegates, false otherwise (event wasn't hooked)
        /// </summary>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        internal static bool FireEvent(Delegate del, object[] args)
        {
            bool ret = false;
            
            if(del != null)
            {
                // Invoke the delegates 1 by 1 instead of in linked list
                // this gives them each a chance to execute
                Delegate[] sinks = del.GetInvocationList();

                foreach(Delegate sink in sinks)
                {
                    try
                    {
                        sink.DynamicInvoke(args);
                    }
                    catch(Exception e)
                    {
                        eventLog.WriteEntry(string.Format(CultureInfo.CurrentCulture, 
                            Strings.ErrorCallingAnEventDelegate, e.ToString()), EventLogEntryType.Error, 
                            (int)RtpEL.ID.Error);
                    }
                }

                ret = true;
            }

            return ret;
        }
Пример #45
0
        private static object InternalSafeInvoke(Delegate deleg, object[] arguments)
        {
            var dynamicInvoker = GetDynamicInvoker(deleg);
            var invocationList = deleg.GetInvocationList();
            if (invocationList.Length < 2)
            {
                // nothing to worry about, invoke as is
                return dynamicInvoker(deleg, arguments);
            }

            // run all delegates and gather exceptions being thrown
            var exceptions = new List<Exception>();
            var result = default(object);
            foreach (var d in invocationList)
            {
                try
                {
                    result = dynamicInvoker(d, arguments);
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex.PreserveStackTrace());
                }
            }

            // return the last result or rethrow exceptions
            if (!exceptions.Any())
            {
                return result;
            }

            #if !FX3
            if (exceptions.Count == 1)
            {
                throw exceptions.First();
            }

            // .NET 4.0 only
            throw new AggregateException(exceptions);
            #else
            throw exceptions.First();
            #endif
        }
Пример #46
0
        /// <summary>
        /// Raises the event encapsulated by the supplied
        /// <paramref name="source"/>, passing the supplied <paramref name="arguments"/>
        /// to the event.
        /// </summary>
        /// <param name="source">The event to be raised.</param>
        /// <param name="arguments">The arguments to the event.</param>
        /// <returns>a map of sink/exception entries that occurred during event raising</returns>
        public virtual IEventExceptionsCollector Raise(Delegate source, params object[] arguments)  
        {
            EventExceptionsCollector exceptions = new EventExceptionsCollector();

            if (source != null)
            {
                Delegate [] delegates = source.GetInvocationList ();
                foreach (Delegate sink in delegates) 
                {
                    Invoke (sink, arguments, exceptions);
                }
            }
            return exceptions;
        }
Пример #47
0
 public static bool Contains(this System.Delegate del, string methodName)
 {
     return(!System.Array.TrueForAll(del.GetInvocationList(), invoker => invoker.Method.Name != methodName));
 }