Skip to content

Instantly share code, notes, and snippets.

@ws6
Created August 26, 2013 21:47
Show Gist options
  • Save ws6/6347071 to your computer and use it in GitHub Desktop.
Save ws6/6347071 to your computer and use it in GitHub Desktop.

Revisions

  1. ws6 created this gist Aug 26, 2013.
    79 changes: 79 additions & 0 deletions libhub.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,79 @@
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    using System.Text.RegularExpressions;
    namespace checkhub.libhub
    {
    public delegate bool processResult(object result);
    public static class hub
    {
    public static List <Type> findsubclass( Type type)
    {
    List<Type> types= new List<Type>();
    var asm = Assembly.GetAssembly(type);
    foreach (var t in asm.GetTypes()){
    if (t.IsSubclassOf(type))
    {
    types.Add(t);
    //Console.WriteLine("{0}", t.Name);
    }
    }
    return types;
    }
    public static MethodInfo[] getMethods(Type type)
    {
    return type.GetMethods();
    }

    public static List<object>
    initObjects( ref Dictionary<string, object> param, List <Type> types )
    {
    var ret=new List<object>();
    foreach(var type in types)
    {
    var o=Activator.CreateInstance(type, param);
    ret.Add(o);
    }
    return ret;
    }

    //a callback function

    public static bool callMethods(object obj, string filter="^Jifeng",processResult saverst=null ,bool debug=true )
    {
    Type t = obj.GetType();
    bool allsucceed = true;
    foreach(var method in getMethods(t))
    {
    Match match = Regex.Match(method.Name, filter);
    if (match.Success)
    {
    var result = t.InvokeMember(method.Name,
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
    null, obj, null);
    if (saverst!=null && ! saverst(result))
    allsucceed = false;
    }

    }
    return allsucceed;
    }

    public static bool runAll(Type basetype, ref Dictionary<string, object> param)
    {
    List <Type> types = findsubclass(basetype);
    var objs = initObjects(ref param, types);
    bool allGood = true;
    foreach(var obj in objs)
    {
    if( !callMethods(obj))
    allGood=false;
    }
    return allGood;
    }

    }

    }