public static class UIExtensioins
{
public class Inclusion
{
public string ComponentTypeFullName { get; set; }
public string EventName { get; set; }
public string[] SenderPropertyNames { get; set; }
public string[] EventArgsPropertyNames { get; set; }
}
public static void AttachLoggerToUIEvent(this Form f, IContainer components,ListinclusionList)
{
foreach (Inclusion i in inclusionList)
{
foreach (Component c in FindComponent(f, i.ComponentTypeFullName, components))
{
AttacheEventHandler(c, i);
}
}
}
public static IEnumerableFindComponent(Control ownerControl,string typeFullName, IContainer containter)
{
bool topComponentFound = false;
foreach (Component c1 in containter.Components)
if (c1.GetType().FullName == typeFullName)
{
topComponentFound = true;
yield return c1;
}
if (topComponentFound) yield break;
foreach (Control c1 in ownerControl.Controls)
{
if (c1.GetType().FullName == typeFullName) yield return c1;
else foreach (Control c2 in FindComponent(c1, typeFullName, containter))
if (c2.GetType().FullName == typeFullName) yield return c2;
}
}
public static void Log(Inclusion i, object sender, T args) where T : EventArgs
{
string logMsg="";
StringBuilder sb = new StringBuilder();
try
{
foreach (string s in i.SenderPropertyNames)
{
if (s != null)
{
PropertyInfo pi = sender.GetType().GetProperty(s);
object v = pi.GetValue(sender, null);
sb.Append(s + "=" + v + ";");
}
}
foreach (string s in i.EventArgsPropertyNames)
{
if (s != null)
{
string[] parts = s.Split('.');
PropertyInfo pi;
object v = args;
for (int k = 0; k < parts.Length; k++)
{
pi = v.GetType().GetProperty(parts[k]);
v = pi.GetValue(v, null);
}
sb.Append(s + "=" + v + ";");
}
}
string Name = "";
Control c = sender as Control;
if (c != null) Name = c.Parent.Name + ":" + c.Name;
logMsg = Name + " " + i.EventName + " " + sb.ToString();
}
catch (Exception ex)
{
logMsg = ex.Message + " " + ex.InnerException.Message + " " + ex.StackTrace;
}
finally
{
Action act = delegate
{
Console.WriteLine(logMsg);
ILog LOG = LogManager.GetLogger(typeof(TradeEntryMainForm));
LOG.Info(logMsg);
};
act.BeginInvoke(ar => { try { act.EndInvoke(ar); } catch { } }, null);
}
}
private static void AttacheEventHandler(Component c, Inclusion i)
{
foreach (EventInfo ei in c.GetType().GetEvents())
{
if (c.GetType().FullName == i.ComponentTypeFullName && ei.Name == i.EventName)
{
Type eventArgsType = ei.EventHandlerType.GetMethod("Invoke").GetParameters()[1].ParameterType;
MethodInfo mi = typeof(UIExtensioins).GetMethod("Log",
BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(eventArgsType
);
ei.AddEventHandler(c,
Delegate.CreateDelegate(ei.EventHandlerType, i, mi));
}
}
}
}
Monday, November 1, 2010
Dynamically Create Event Handler
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment