Esempio n. 1
0
		internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args)
		{
			try
			{
				if (md != null)
				{
					Delegate[] invocationList = md.GetInvocationList();
					for (int i = 0; i < (int)invocationList.Length; i++)
					{
						Delegate @delegate = invocationList[i];
						try
						{
							object[] objArray = new object[2];
							objArray[0] = this.sender;
							objArray[1] = args;
							@delegate.DynamicInvoke(objArray);
						}
						catch
						{
						}
					}
				}
			}
			catch
			{
			}
		}
Esempio n. 2
0
        public static void InvokeDelegates(MulticastDelegate mDelegate, object sender, EventArgs e)
        {
            if (mDelegate == null)
                return;

            Delegate[] delegates = mDelegate.GetInvocationList();
            if (delegates == null)
                return;

            // Invoke delegates within their threads
            foreach (Delegate _delegate in delegates)
            {
                if (_delegate.Target.GetType().ContainsGenericParameters)
                {
                    Console.WriteLine("Cannot invoke event handler on a generic type.");
                    return;
                }

                object[] contextAndArgs = { sender, e };
                ISynchronizeInvoke syncInvoke = _delegate.Target as ISynchronizeInvoke;
                {
                    if (syncInvoke != null)
                    {
                        // This case applies to the situation when Delegate.Target is a 
                        // Control with an open window handle.
                        syncInvoke.Invoke(_delegate, contextAndArgs);
                    }
                    else
                    {
                        _delegate.DynamicInvoke(contextAndArgs);
                    }
                }
            }
        }
 private void InvokeHandler( MulticastDelegate handlerList, EventArgs e )
 {
     object[] args = new object[] { this, e };
     foreach( Delegate handler in handlerList.GetInvocationList() )
     {
         object target = handler.Target;
         System.Windows.Forms.Control control
             = target as System.Windows.Forms.Control;
         try
         {
             if ( control != null && control.InvokeRequired )
                 //control.Invoke( handler, args );
                 control.BeginInvoke(handler, args);
             else
                 handler.Method.Invoke( target, args );
         }
         catch( Exception ex )
         {
             // TODO: Stop rethrowing this since it goes back to the
             // Test domain which may not know how to handle it!!!
             Console.WriteLine( "Exception:" );
             Console.WriteLine( ex );
             //throw new TestEventInvocationException( ex );
             //throw;
         }
     }
 }
Esempio n. 4
0
 static void DisplayMulticastInfo(MulticastDelegate md)
 {
     foreach(var d in md.GetInvocationList())
     {
         DisplayDelegateInfo(d);
     }
 }
Esempio n. 5
0
 /// <summary>
 /// Raise an event with routines-delegates.
 /// </summary>
 /// <param name="evnt">Event to raise</param>
 /// <param name="action">Routines to start</param>
 /// <returns>Routine</returns>
 public static IEnumerator YieldForEach(this System.MulticastDelegate evnt, System.Func <System.Delegate, Coroutine> action)
 {
     if (evnt != null)
     {
         System.Delegate[] delegates = evnt.GetInvocationList();
         foreach (System.Delegate d in delegates)
         {
             yield return(action(d));
         }
     }
 }
Esempio n. 6
0
		public static object[] SafeMultiInvoke(MulticastDelegate delegateToFire, params object[] parameters )
		{	
			Delegate[] invocationList = delegateToFire.GetInvocationList();		
			
			object[] retvals = new object[invocationList.Length];
			int i=0;			
			
			foreach (Delegate dlg in invocationList)
			{
				retvals[i++] = SafeInvoke(dlg, parameters);		
			}
			return retvals;
		}			
        public string TestGetName()
        {
            // return this.OnGetName();

            System.MulticastDelegate m     = (System.MulticastDelegate) this.OnGetName;
            System.Delegate[]        dlist = m.GetInvocationList();
            string[] results = new string[dlist.Length];

            for (int i = 0; i < dlist.Length; ++i)
            {
                object[] p = { /*put your parameters here*/ };
                results[i] = System.Convert.ToString(dlist[i].DynamicInvoke(p));
            }

            // return string.Join(",", results);
            return(Coalesce(results));
        }
Esempio n. 8
0
 public static void TryInvoke(this System.MulticastDelegate theDelegate, params object[] args)
 {
     if (theDelegate == null)
     {
         return;
     }
     foreach (Delegate handler in theDelegate.GetInvocationList())
     {
         try
         {
             handler.DynamicInvoke(args);
         }
         catch (Exception ex)
         {
             Logger.LogError("Error in MulticastDelegate " + handler.GetType().Name + ": " + ex.ToString());
         }
     }
 }
        public string TestGetName_real(System.Type t, string name)
        {
            System.MulticastDelegate m     = (System.MulticastDelegate) this.OnGetName;
            System.Delegate[]        dlist = m.GetInvocationList();

            for (int i = 0; i < dlist.Length; ++i)
            {
                // object[] p = { t, name };
                object[] p   = { /*put your parameters here*/ };
                string   ret = System.Convert.ToString(dlist[i].DynamicInvoke(p));
                if (!string.IsNullOrEmpty(ret) && ret.Trim() != string.Empty)
                {
                    return(ret);
                }
            }

            // return string.Join(",", results);
            // return Coalesce(results);
            throw new System.ArgumentException("Cannot find dependency with this arguments.");
        }
Esempio n. 10
0
        public static void InvokeMulticast(object sender, MulticastDelegate md, EventArgs e)
        {
            if (md == null)
                return;

            foreach (StdMulticastDelegation Caster in md.GetInvocationList())
            {
                ISynchronizeInvoke SyncInvoke = Caster.Target as ISynchronizeInvoke;
                try
                {
                    if (SyncInvoke != null && SyncInvoke.InvokeRequired)
                        SyncInvoke.Invoke(Caster, new object[] { sender, e });
                    else
                        Caster(sender, e);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("Event handling failed. \n");
                    Console.WriteLine("{0}:\n", ex.ToString());
                }
            }
        }
 internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args)
 {
     try
     {
         if (md != null)
         {
             foreach (Delegate delegate2 in md.GetInvocationList())
             {
                 try
                 {
                     delegate2.DynamicInvoke(new object[] { this.sender, args });
                 }
                 catch
                 {
                 }
             }
         }
     }
     catch
     {
     }
 }
Esempio n. 12
0
 internal static bool ContainsDelegate(MulticastDelegate source, Delegate d)
 {
   if (null != source && null != d)
   {
     Delegate[] list = source.GetInvocationList();
     if (null != list)
     {
       for (int i = 0; i < list.Length; i++)
       {
         if (list[i].Equals(d))
           return true;
       }
     }
   }
   return false;
 }
Esempio n. 13
0
 internal static Delegate FindBuilder(MulticastDelegate mcd)
 {
   if (mcd != null)
   {
     Delegate[] invocationList = mcd.GetInvocationList();
     for (int i = 0; i < invocationList.Length; i++)
     {
       if (invocationList[i].Target is DbCommandBuilder)
       {
         return invocationList[i];
       }
     }
   }
   return null;
 }
Esempio n. 14
0
        public static void ConfigureStaticEventHandler(object obj, string objEventName, string handlerMethodName,
                                                       bool attach)
        {
            // use reflection to assign delegate method to event
            // get type for the handler class (this class) from the handler assembly
            Type handlerClassType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;

            if (handlerClassType == null)
            {
                throw new Exception(String.Format("Cannot get handler class type"));
            }

#if BP_DO_EXISTING_DELEGATE_TEST
            // determine if required delegate exists
            bool delegateExists = false;

            // get the delegate fields for the given event
            // note that this will only work for field-like events.
            // notably this approach works for the Dubrovnik unit tests but fails with EntityFramework objects!
            FieldInfo eventFieldInfo = obj.GetType().GetField(objEventName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (eventFieldInfo != null)
            {
                System.MulticastDelegate eventHandler = eventFieldInfo.GetValue(obj) as System.MulticastDelegate;
                if (eventHandler != null)
                {
                    foreach (Delegate dg in eventHandler.GetInvocationList())
                    {
                        MethodInfo delegateMethodInfo = dg.Method;

                        // does the existing delegate method target the incoming method
                        if (delegateMethodInfo.Name == handlerMethodName &&
                            delegateMethodInfo.DeclaringType == handlerClassType && dg.Target == null)
                        {
                            delegateExists = true;
                            break;
                        }
                    }
                }
            }
            else


            // we only want to register events once against this object.
            // we similarly only want to delete existing delegates
            if (attach && delegateExists || !attach && !delegateExists)
            {
                return;
            }
#endif
            // get info for the event from the type.
            // note that if we are attaching to a static event handler then the obj parameter will be a System.Type instance.
            Type t;
            if (obj is System.Type)
            {
                t = (Type)obj;
            }
            else
            {
                t = obj.GetType();
            }
            EventInfo evInfo = t.GetEvent(objEventName);

            if (evInfo == null)
            {
                throw new Exception(String.Format("Cannot locate event: {0} on object of type : {1}", objEventName, obj.GetType().ToString()));
            }

            // get method info for the managed handler method
            MethodInfo handlerMethod = handlerClassType.GetMethod(handlerMethodName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static);
            if (handlerMethod == null)
            {
                throw new Exception(String.Format("Cannot get method info for handler : {0}", handlerMethodName));
            }

            // create delegate
            Type     delegateType = evInfo.EventHandlerType;
            Delegate theDelegate  = Delegate.CreateDelegate(delegateType, null, handlerMethod);
            if (theDelegate == null)
            {
                throw new Exception(String.Format("Cannot create delegate for handler : {0}", handlerMethodName));
            }

            // invoke the add | remove method on the event
            MethodInfo evMethod = attach ? evInfo.GetAddMethod() : evInfo.GetRemoveMethod();
            Object[]   args     = { theDelegate };
            evMethod.Invoke(obj, args);
        }
Esempio n. 15
0
        public Structure FindAllTargets(object obj)
        {
            Dictionary <Delegate, object> delegate_to_instance = new Dictionary <Delegate, object>();
            Delegate     lambda_delegate = (Delegate)obj;
            BindingFlags findFlags       = BindingFlags.NonPublic |
                                           BindingFlags.Public |
                                           BindingFlags.Static |
                                           BindingFlags.Instance |
                                           BindingFlags.InvokeMethod |
                                           BindingFlags.OptionalParamBinding |
                                           BindingFlags.DeclaredOnly;

            _control_flow_graph.Add(Campy.Types.Utils.ReflectionCecilInterop.ConvertToMonoCecilMethodDefinition(lambda_delegate.Method));
            _control_flow_graph.ExtractBasicBlocks();

            // Construct graph containing all objects used in lambda.
            StackQueue <object> stack = new StackQueue <object>();

            stack.Push(lambda_delegate);
            Campy.Graphs.GraphLinkedList <object> data_graph = new GraphLinkedList <object>();
            while (stack.Count > 0)
            {
                object node = stack.Pop();

                // Case 1: object is multicast delegate.
                // A multicast delegate is a list of delegates called in the order
                // they appear in the list.
                System.MulticastDelegate md = node as System.MulticastDelegate;
                if (md != null)
                {
                    foreach (System.Delegate node2 in md.GetInvocationList())
                    {
                        if ((object)node2 != (object)node)
                        {
                            if (Options.Singleton.Get(Options.OptionType.DisplayStructureComputation))
                            {
                                System.Console.WriteLine("Pushing2 " + MyToString(node2));
                            }
                            stack.Push(node2);
                        }
                    }
                    // Note, if multicast delegate, then it does not make sense to continue.
                    // Handle normal delegates.
                    //continue;
                }

                // Case 2: object is plain delegate.
                System.Delegate del = node as System.Delegate;
                if (del != null)
                {
                    object target = del.Target;
                    if (target == null)
                    {
                        // If target is null, then the delegate is a function that
                        // uses either static data, or does not require any additional
                        // data. If target isn't null, then it's probably a class.
                        target = Activator.CreateInstance(del.Method.DeclaringType);
                        if (data_graph.Vertices.Contains(target))
                        {
                            continue;
                        }
                        if (!delegate_to_instance.ContainsKey(del))
                        {
                            Debug.Assert(!TypesUtility.IsBaseType(target.GetType(), typeof(Delegate)));
                            data_graph.AddVertex(target);
                            delegate_to_instance.Add(del, target);
                            stack.Push(target);
                        }
                    }
                    else
                    {
                        // Target isn't null for delegate. Most likely, the method
                        // is part of the target, so let's assert that.
                        bool found = false;
                        foreach (System.Reflection.MethodInfo mi in target.GetType().GetMethods(findFlags))
                        {
                            if (mi == del.Method)
                            {
                                found = true;
                                break;
                            }
                        }
                        Debug.Assert(found);
                        if (Options.Singleton.Get(Options.OptionType.DisplayStructureComputation))
                        {
                            System.Console.WriteLine("Pushing " + MyToString(target));
                        }
                        if (delegate_to_instance.ContainsKey(del))
                        {
                            Debug.Assert(delegate_to_instance[del] == target);
                        }
                        else
                        {
                            delegate_to_instance.Add(del, target);
                        }
                        stack.Push(target);
                    }
                    continue;
                }

                if (data_graph.Vertices.Contains(node))
                {
                    continue;
                }

                Debug.Assert(!TypesUtility.IsBaseType(node.GetType(), typeof(Delegate)));
                data_graph.AddVertex(node);

                // Case 3: object is a class, and potentially could point to delegate.
                // Examine all fields, looking for list_of_targets.

                Type target_type = node.GetType();

                FieldInfo[] target_type_fieldinfo = target_type.GetFields();
                foreach (var field in target_type_fieldinfo)
                {
                    var value = field.GetValue(node);
                    if (value != null)
                    {
                        if (field.FieldType.IsValueType)
                        {
                            continue;
                        }
                        if (TypesUtility.IsCampyArrayType(field.FieldType))
                        {
                            continue;
                        }
                        if (TypesUtility.IsSimpleCampyType(field.FieldType))
                        {
                            continue;
                        }
                        // chase pointer type.
                        if (Options.Singleton.Get(Options.OptionType.DisplayStructureComputation))
                        {
                            System.Console.WriteLine("Pushingf " + MyToString(value));
                        }
                        stack.Push(value);
                    }
                }
            }

            if (Options.Singleton.Get(Options.OptionType.DisplayStructureComputation))
            {
                System.Console.WriteLine();
                System.Console.WriteLine("Dump of nodes.");
                foreach (object node in data_graph.Vertices)
                {
                    System.Console.WriteLine("Node "
                                             + MyToString(node));
                    System.Console.WriteLine("typeof node = "
                                             + node.GetType());
                    System.Console.WriteLine("Node "
                                             + (((node as Delegate) != null) ? "is " : "is not ")
                                             + "a delegate.");
                    System.Console.WriteLine();
                }
            }

            // Add edges.
            foreach (object node in data_graph.Vertices)
            {
                Type node_type = node.GetType();

                FieldInfo[] node_type_fieldinfo = node_type.GetFields();
                foreach (var field in node_type_fieldinfo)
                {
                    if (field.FieldType.IsValueType)
                    {
                        continue;
                    }
                    if (TypesUtility.IsCampyArrayType(field.FieldType))
                    {
                        continue;
                    }
                    if (TypesUtility.IsSimpleCampyType(field.FieldType))
                    {
                        continue;
                    }
                    var value = field.GetValue(node);
                    if (value == null)
                    {
                    }
                    else if (TypesUtility.IsBaseType(value.GetType(), typeof(Delegate)))
                    {
                        Delegate del          = value as Delegate;
                        object   value_target = del.Target;
                        if (value_target == node)
                        {
                            ;
                        }
                        else if (value_target != null)
                        {
                            Debug.Assert(data_graph.Vertices.Contains(node));
                            Debug.Assert(data_graph.Vertices.Contains(value_target));
                            data_graph.AddEdge(node, value_target);
                        }
                        else
                        {
                            value_target = delegate_to_instance[del];
                            if (value_target != node)
                            {
                                Debug.Assert(data_graph.Vertices.Contains(node));
                                Debug.Assert(data_graph.Vertices.Contains(value_target));
                                data_graph.AddEdge(node, value_target);
                            }
                        }
                    }
                    else
                    {
                        Debug.Assert(data_graph.Vertices.Contains(node));
                        Debug.Assert(data_graph.Vertices.Contains(value));
                        data_graph.AddEdge(node, value);
                    }
                }
            }

            if (Options.Singleton.Get(Options.OptionType.DisplayStructureComputation))
            {
                foreach (object node in data_graph.Vertices)
                {
                    System.Console.WriteLine("Node "
                                             + MyToString(node));
                    System.Console.WriteLine("typeof node = "
                                             + node.GetType());
                    System.Console.WriteLine("Node "
                                             + (((node as Delegate) != null) ? "is " : "is not ")
                                             + "a delegate.");
                    foreach (object succ in data_graph.Successors(node))
                    {
                        System.Console.WriteLine("-> "
                                                 + succ.GetHashCode() + " " + MyToString(succ));
                    }
                    System.Console.WriteLine();
                }
                System.Console.WriteLine();
            }

            Structure res = Structure.Initialize(delegate_to_instance, lambda_delegate.Method, data_graph, _control_flow_graph);

            if (Options.Singleton.Get(Options.OptionType.DisplayStructureComputation))
            {
                res.Dump();
            }

            return(res);
        }
Esempio n. 16
0
 internal Delegate[] GetDelegatesWithNonTransientTargets(MulticastDelegate mDelegate)
 {
     return mDelegate.GetInvocationList().Where(x => x.Target == null || !CheckTransient(x.Target)).ToArray();
 }
        /// <summary>
        /// Custom handler for firing a WMI event to a list of delegates. We use
        /// the process thread pool to handle the firing.
        /// </summary>
        /// <param name="md">The MulticastDelegate representing the collection
        /// of targets for the event</param>
        /// <param name="args">The accompanying event arguments</param>
        internal void FireEventToDelegates (MulticastDelegate md, ManagementEventArgs args)
        {
            try 
            {
                if (null != md)
                {
#if USEPOOL
                    Delegate[] delegateList = md.GetInvocationList ();

                    if (null != delegateList)
                    {
                        int numDelegates = delegateList.Length;
                        AutoResetEvent[] waitHandles = new AutoResetEvent [numDelegates];

                        /*
                         * For each target delegate, queue a request to the 
                         * thread pool to handle the POST. We pass as state the 
                         *  1) Target delegate
                         *  2) Event args
                         *  3) AutoResetEvent that the thread should signal to 
                         *     indicate that it is done.
                         */
                        for (int i = 0; i < numDelegates; i++)
                        {
                            waitHandles [i] = new AutoResetEvent (false);
                            ThreadPool.QueueUserWorkItem (
                                    new WaitCallback (this.FireEventToDelegate),
                                    new WmiEventState (delegateList[i], args, waitHandles[i]));
                        }

                        /*
                         * We wait for all the delegates to signal that they are done.
                         * This is because if we return from the IWbemObjectSink callback
                         * before they are all done, it is possible that a delegate will
                         * begin to process the next callback before the current callback
                         * processing is done.
                         */
                        WaitHandle.WaitAll (waitHandles, 10000, true);
                        }
                    }
#endif
                    foreach (Delegate d in md.GetInvocationList())
                    {
                        try 
                        {
                            d.DynamicInvoke (new object [] {this.sender, args});    
                        } 
                        catch
                        {
                        }
                    }
                }
            }
Esempio n. 18
0
        public static void ConfigureStaticEventHandler(object obj, string objEventName, string handlerMethodName, bool attach)
        {
            // use reflection to assign delegate method to event
            // get type for the handler class (this class) from the handler assembly
            Type handlerClassType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;

            if (handlerClassType == null)
            {
                throw new Exception(String.Format("Cannot get handler class type"));
            }

            // determine if required delegate exists
            bool delegateExists = false;

            // get the delegate fields for the given event.
            // NOTE: this is unreliable and ONLY works for field-like events
            FieldInfo eventFieldInfo = obj.GetType().GetField(objEventName, BindingFlags.NonPublic | BindingFlags.Instance);

            if (eventFieldInfo != null)
            {
                System.MulticastDelegate eventHandler = eventFieldInfo.GetValue(obj) as System.MulticastDelegate;
                if (eventHandler != null)
                {
                    foreach (Delegate dg in eventHandler.GetInvocationList())
                    {
                        MethodInfo delegateMethodInfo = dg.Method;

                        Console.WriteLine("Method name = {0} ", delegateMethodInfo.Name);
                        Console.WriteLine("Method declaring type = {0} ", delegateMethodInfo.DeclaringType);
                        Console.WriteLine("Delegate target = {0} ", dg.Target);

                        // does the existing delegate method target the incoming method
                        if (delegateMethodInfo.Name == handlerMethodName && delegateMethodInfo.DeclaringType == handlerClassType && dg.Target == null)
                        {
                            delegateExists = true;
                            break;
                        }
                    }
                }
            }

            // we only want to register events once against this object.
            // we similarly only want to delete existing delegates
            if (attach && delegateExists || !attach && !delegateExists)
            {
                Console.WriteLine("DELEGATE EXISTS");
                return;
            }
            Console.WriteLine("DELEGATE WILL BE ADDED");

            // get info for the event
            EventInfo evInfo = obj.GetType().GetEvent(objEventName);

            if (evInfo == null)
            {
                throw new Exception(String.Format("Cannot locate event: {0} on object of type : {1}", objEventName, obj.GetType().ToString()));
            }

            // get method info for the managed handler method
            MethodInfo handlerMethod = handlerClassType.GetMethod(handlerMethodName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static);

            if (handlerMethod == null)
            {
                throw new Exception(String.Format("Cannot get method info for handler : {0}", handlerMethodName));
            }

            // create delegate
            Type     delegateType = evInfo.EventHandlerType;
            Delegate theDelegate  = Delegate.CreateDelegate(delegateType, null, handlerMethod);

            if (theDelegate == null)
            {
                throw new Exception(String.Format("Cannot create delegate for handler : {0}", handlerMethodName));
            }

            // invoke the add | remove method on the event
            MethodInfo evMethod = attach ? evInfo.GetAddMethod() : evInfo.GetRemoveMethod();

            Object[] args = { theDelegate };
            evMethod.Invoke(obj, args);
        }