Created
October 23, 2015 11:58
-
-
Save khellang/0a25fbb319845fc388dd to your computer and use it in GitHub Desktop.
Check namespace of all MVC controllers in a solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Program | |
{ | |
private const string ControllerType = "System.Web.Mvc.Controller"; | |
public static void Main(string[] args) | |
{ | |
MainAsync(args).Wait(); | |
} | |
private static async Task MainAsync(string[] args) | |
{ | |
var workspace = MSBuildWorkspace.Create(); | |
var solution = await workspace.OpenSolutionAsync(args[0]); | |
foreach (var project in solution.Projects) | |
{ | |
// Compile the project. | |
var compilation = await project.GetCompilationAsync(); | |
// Get a symbol instance for the MVC controller type. | |
var controllerBaseType = compilation.GetTypeByMetadataName(ControllerType); | |
foreach (var document in project.Documents) | |
{ | |
// Get all controllers in document. | |
var controllerTypes = await document.GetControllerTypes(compilation, controllerBaseType); | |
foreach (var controllerType in controllerTypes) | |
{ | |
// Check if controller has the correct namespace. | |
if (!controllerType.ContainingNamespace.Name.Equals("Controllers")) | |
{ | |
// Do whatever... | |
} | |
} | |
} | |
} | |
} | |
private static async Task<IEnumerable<INamedTypeSymbol>> GetControllerTypes(this Document document, Compilation compilation, INamedTypeSymbol controllerType) | |
{ | |
var syntaxTree = await document.GetSyntaxTreeAsync(); | |
var semanticModel = compilation.GetSemanticModel(syntaxTree); | |
var rootNode = await syntaxTree.GetRootAsync(); | |
return rootNode.DescendantNodes() | |
.OfType<ClassDeclarationSyntax>() | |
.Select(x => semanticModel.GetDeclaredSymbol(x)) | |
.Where(x => x.IsAssignableTo(controllerType)); | |
} | |
private static bool IsAssignableTo(this ITypeSymbol symbol, ISymbol other) | |
{ | |
if (symbol.Equals(other)) | |
{ | |
return true; | |
} | |
var baseType = symbol.BaseType; | |
if (baseType == null) | |
{ | |
return false; | |
} | |
return baseType.IsAssignableTo(other); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment