/// /// (c) 2007 James A Briant /// /// Permission is granted to use or modify this source code provided that /// a) this notice is kept intact /// b) if you make any modications to this file you assign the /// copyright of those modifications to James Briant. /// c) you acknowledge that Mr. Briant offers no warranty /// and will not be liable for any loss, damages, time, etc. /// /// Any doubt, email me: firstname (nospace) lastname at persuasivesoftware.com /// using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Reflection; using DevDriven.P4Vs.Common; using Microsoft.VisualStudio.Shell; namespace DevDriven.P4Vs.Common { internal class OleCommandHandlerGenerator { class Handler { public CommandID CommandID; public MethodInfo Exec; public MethodInfo Query; } public static void GenerateCommands(IMenuCommandService mserv, object target) { if (mserv == null) throw new ArgumentNullException("mserv"); if (target == null) throw new ArgumentNullException("target"); Type t = target.GetType(); Dictionary handlers = new Dictionary(); foreach (MethodInfo info in t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)) { object[] atts = info.GetCustomAttributes(typeof(OleCommandHandlerAttribute), true); foreach (OleCommandHandlerAttribute och in atts) { if (atts.Length > 0) { Handler h; if (handlers.ContainsKey(och.CommandID)) { h = handlers[och.CommandID]; } else { h = new Handler(); handlers.Add(och.CommandID, h); } if (och.Kind == HandlerKind.Exec) { h.Exec = info; } else { h.Query = info; } } } } foreach (KeyValuePair pair in handlers) { EventHandler execDelegate = null; EventHandler queryDelegate = null; if (pair.Value.Exec != null) execDelegate = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), target, pair.Value.Exec); if (pair.Value.Query != null) queryDelegate = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), target, pair.Value.Query); OleMenuCommand omc = new OleMenuCommand(execDelegate, null, queryDelegate, pair.Key); mserv.AddCommand(omc); } } } }