4

We've got a huge ASP.NET MVC 3 application. We need to count how many public methods we have in classes where currentClass is System.Web.Mvc.Controller.

Any class that meets this criteria will have a base namespace of 'AwesomeProduct.Web', but there's no guarantee beyond that what namespace these classes may fall under, or how many levels of depth there are.

What's the best way to figure this out?

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
core
  • 32,451
  • 45
  • 138
  • 193
  • 1
    I imagine some usage of reflection will be your best option. Start here: http://stackoverflow.com/a/79738/74757. Then with the collection of class types, you can again use reflection to get the public methods. You can go a step further and check for any `NonActionAttribute` attributes too. – Cᴏʀʏ Mar 07 '13 at 22:37

1 Answers1

10

Some reflection and LINQ like this should do it

var actionCount = typeof(/*Some Controller Type In Your MVC App*/)
                    .Assembly.GetTypes()
                    .Where(t => typeof(Controller).IsAssignableFrom(t))
                    .Where(t => t.Namespace.StartsWith("AwesomeProduct.Web"))
                    .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                    .Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType))
                    .Where(m => !m.IsAbstract)
                    .Where(m => m.GetCustomAttribute<NonActionAttribute>() == null)
                    .Count();

This does not cater for async controller actions.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266