MvcSitemaps Vs T4MVC and test for all controllers

One of the tasks have performed lately in our massive web-application is restructuring menu. And for the menu to work correctly we had to make sure that every page is somewhere on the menu.

For Menu generation we use MvcSitemapProvider. And for strongly-typed references to our controllers/actions we generate static classes via T4MVC. Task of making sure that every controller action (out of ~600) has a SiteMapAttribute is very tedious. And with development of new features, this can easily be forgotten, leading to bugs in our menu. So we decided to write a test. This turned out to be yet another massive reflection exercise and it took a while to get it correctly. So I’d like to share this with you.

Theory of the test are simple – find all controllers, on every controller find all the methods and check that every method has a custom attribute of type
MvcSiteMapNodeAttribute. But in practice this was more complex because we used T4MVC.

Continue reading

Find all descendants of a type

Quite often for DI auto-wiring I need to find all classes that implement a certain interface or inherit from some base abstract class. And reflection for that is brilliant. But I can never remember how to find these types, so every time I need to look up my old code. So I’ll record that in this blog. Here you go:

var profiles = Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x))
    .ToList();

This will give a list of types that all inherit from class Profile, but actually excludes the Profile class itself.