Skip to content

Instantly share code, notes, and snippets.

@jkuemerle
Created August 11, 2012 03:38
Show Gist options
  • Select an option

  • Save jkuemerle/3320454 to your computer and use it in GitHub Desktop.

Select an option

Save jkuemerle/3320454 to your computer and use it in GitHub Desktop.
ASP.NET MVC Controller verification aspect
using System;
using System.IO;
using System.Web.Mvc;
using PostSharp.Aspects;
using PostSharp.Extensibility;
namespace WebApplication.Aspects {
[Serializable]
public class VerifyControllerAttribute : TypeLevelAspect {
public override bool CompileTimeValidate(Type type) {
if (TypeIsIController(type) && IsPublicClass(type) && !NameMeetsConvention(type)) {
Message.Write(GetLocation(type), SeverityType.Error, "1000", "Controller: {0} does not meet ASP.NET MVC naming convention. Type name must end with Controller",type.Name);
return false;
}
if (NameMeetsConvention(type) && IsPublicClass(type) && !TypeIsIController(type) ) {
Message.Write(GetLocation(type), SeverityType.Error, "1000", "Controller: {0} is not an IController.", type.Name);
return false;
}
if (NameMeetsConvention(type) && TypeIsIController(type) && !IsPublicClass(type)) {
Message.Write(GetLocation(type), SeverityType.Error, "1000", "Controller: {0} needs to be public, non-nested and non-abstract.", type.Name);
return false;
}
return true;
}
private bool NameMeetsConvention(Type type) {
return type.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase);
}
private bool TypeIsIController(Type type) {
return typeof(IController).IsAssignableFrom(type);
}
public bool IsPublicClass(Type type) {
return type != null && type.IsPublic && type.IsClass && !type.IsAbstract;
}
private PostSharp.MessageLocation GetLocation(Type type) {
var loc = PostSharp.MessageLocation.Unknown;
string projectFile = PostSharpEnvironment.Current.CurrentProject.EvaluateExpression("{$MSBuildProjectFullPath}");
bool usePostSharp = false;
bool.TryParse(PostSharpEnvironment.Current.CurrentProject.EvaluateExpression("{$ParseWithPostSharp}"),out usePostSharp);
if (usePostSharp || !File.Exists(projectFile)) // use PostSharps experimental functionality to find the method location in the code
loc = PostSharp.MessageLocation.Of(type);
else { // otherwise use CodeFreud and Project Roslyn to find the location in the code
var res = CodeFreud.Finder.FindTypeInProject(projectFile, type);
if (null != res)
loc = PostSharp.MessageLocation.Explicit(res.SourceFile.FullName, res.LineNumber, res.ColumnNumber);
}
return loc;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment