Skip to content

Instantly share code, notes, and snippets.

@trayburn
Created April 2, 2015 17:48
Show Gist options
  • Save trayburn/cd9a8fd0b8b66c7f85c8 to your computer and use it in GitHub Desktop.
Save trayburn/cd9a8fd0b8b66c7f85c8 to your computer and use it in GitHub Desktop.
Example of a simple AppConvention written by Tim Rayburn
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
namespace Example.Tests.AppConventions
{
[TestFixture]
public class Controller_Conventions
{
[Test, TestCaseSource("TestCases")]
public void Must_Have_Authorize_Or_AllowAnonymous(Type controller, string name)
{
if (controller.GetCustomAttribute<System.Web.Mvc.AllowAnonymousAttribute>(true) == null &&
controller.GetCustomAttribute<AuthorizationAttribute>(true) == null)
{
Assert.Fail("SECURITY > {0} has neither the Authorize or AllowAnonymous attributes", controller.FullName);
}
}
public static IEnumerable<TestCaseData> TestCases
{
get
{
return Conventions.GetControllers()
.Select(c => new TestCaseData(c, c.Name));
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
namespace Example.Tests.AppConventions
{
public static class Conventions
{
public static IEnumerable<Type> GetTypes()
{
AppDomain appDomain = AppDomain.CurrentDomain;
Assembly[] assemblies = appDomain.GetAssemblies();
IEnumerable<Assembly> ogproAssemblies = assemblies.Where(e => e.FullName.StartsWith("Example"));
IEnumerable<Type> assembliesSelectMany = ogproAssemblies.SelectMany(a => a.GetTypes());
List<Type> list = assembliesSelectMany.ToList();
return list;
}
public static IEnumerable<Type> GetControllers()
{
return Assembly.GetAssembly(typeof(Example.MvcApplication)).GetControllers();
}
public static IEnumerable<Type> GetControllers(this Assembly assm)
{
return assm.GetTypes()
.Where(e => e.IsClass && e.IsPublic && (e.IsAbstract == false))
.Where(e => e.GetInterfaces().Any(i => i == typeof(IController)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment