c# using custom attributes to validate prerequisites for methods, controller APIs

If you have bunch of prerequisites to be validated for more than one method, we could make code more cute by using an attribute.

For normal methods, this new custom attribute’s constructor could throw exception in case of failure.

But throwing exception in Controller API is bad idea. We want to return more gracefully.

Instead of extending Attribute, extend AuthorizeAttribute and override IsAuthorized() [ or AuthorizeCore() ] method to return true or false. This is more graceful way of doing prerequisite check.

I know this AuthroizeAttribute is to check authorization, but we could mis-use it to validate any prerequisites until a better way is available.

/*****************************************************************************************/

using System;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
internal class MustBeAuthorizedAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{

if (preRequsitesFail)

{
return false;

}

return true;
}
}
}

/*****************************************************************************************/

[MustBeAuthorized]
public ActionResult Index()
{
return View();
}

/*****************************************************************************************/

Thanks to @philip instead of AuthroizeAttribute  ActionFilterAttribute is better. We could return any return value (e.g.. MethodNotAllowed, InternalServerError); see https://stackoverflow.com/questions/16822365/web-api-how-to-stop-the-web-pipeline-directly-from-an-onactionexecuting-filter 

notes, unit testing c# mock, stub, shim!

What to unit test?

Some times it feels why the heck are we adding this unit test? Some times did we really added at least minimum required unit tests or not?

I spent good amount of time researching this topic.

My thumb rule is :

Assume you are adding a document with samples directly taken from Unit tests (except Mocking part though) ; We want our Unit tests to test what customer typically do.

Unit Test is a shield:

Unit test works like a shield. It protects from the minute it is born. This unit test shield will protect the code from your future self. This unit test shield will also protect from others working on this piece of code. Mistakes which will break some existing user can be avoided with this unit testing strategy.

Mock Vs Fake(Stub/Shim)

Use whatever works! External DLLs are better faked. But there are some beasts which will have give tough fight to be faked. In that case do not directly call this external DLL, rather call via a thin layer, a layer with zero business logic but with an interface+class design. Then mock this layer instead of trying to fake your external DLL. Unit tests are saved!