Friday, July 13, 2012

Tuesday, July 10, 2012

Filters in ASP.NET MVC

Filters are .NET attributes used to inject extra logic into MVC framework request processing. You can apply filters before and after calling an action method (pre-action and post-action). 

Filters can be used for,
- Custom Authentication
- Custom Authorization (User or Role base)
- Error handling and logging
- User Activity logging
- Data caching and compression

.NET attribute
Attribute are special .NET classes derived from System.Attribute namespace. Used to embed additonal information into compiled code to read at runtime. 

What are global filters?
You can add global filters inside Global.asax file. By using these you don't have to specify filter attributes in each controller and action. You can also add these conditionally. (resource).

There are 5 basic types of filters,

Authorization filters
  • Runs first, before any other filter or action method. 
  • Implements IAuthorizationFilter.
  • Makes security decisions about whether to execute an action method such as performing authentication or validating properties of the request. 
  • AuthroizeAttribute class and RequireHttpsAttribute class are examples of an authorization filter. 
Action filters
  • Runs before and after the action method. 
  • Implements IActionFilter
  • IActionFitler declares two methods
    • OnActionExecuting : runs before the action method
    • OnActionExecuted: runs after the action method
Result filters
  • Runs before and after the action result is executed
  • Implements IResultFilter 
  • IResultFilter declares two methods
    • OnResultExecuting : runs before the ActionResult object is executed
    • OnResultExecuted: runs after the result and perform additional processing of the result such as modifying the HTTP response
  • The OutputCacheAttribute class is an example of a result filter (implementation,  web farm limitations)
  • Extending ASP.NET MVC OutputCache
Exception filters
  • Runs only if another filter, the action method or the action result throws an exception
  • Implements IExceptionFilter
  • Execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. 
  • Can be used for tasks such as logging or displaying error page
  • HandleErrorAttribute class is an example of an exception filter (article). Usually HandleError is added to global filters in MVC projects.
Authentication filters (New in ASP.NET MVC 5, article)
  • Implements IAuthenticationFilter
  • Applied prior to any Authorization filter
  • You have two methods to implement
    • OnAuthentication(AuthenticationContext filterContext)
    • OnAuthenticationChallenge : runs after OnAuthentication. You can perform additional things here



Controller class implements each of the filter interfaces (IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IResultFilter). All above Attributes implements abstract FilterAttribute base class, which then again implements Attribute class. AuthorizeAttribute and HandleErrorAttribute contain useful features you can use without creating derived class.

AuthorizeAttribute Class
  • When you mark an action method with this, access to the action method is restricted to users who are authenticated and authorized.
  • Use AllowAnonymousAttribute attribute to specify that a particular action method is not restricted to only authroized users.
  • Use Roles and Users properties to specify which roles or users are permitted
  • If unauthorized user tries to access MVC framework returns a 401 HTTP status code
  • If you derive from the AuthorizeAttribute class, the derived type should be thread safe. Therefore do not store state in an instance of the type itself. Instead, store state per request in the Items property which is accessible through context objects passed to AuthorizeAttribute.
  • See examples here

Tuesday, July 3, 2012

Generics in C#

Introduced in .NET 2.0, Generics introduced type parameters to the framework. Generics makes it possible to design classes or methods to defer the specification of types until the class or method is declared and instantiated by the client code. 



Generic types combines reusability, type safety and efficiency when compared to non-generic counterparts. Generics are frequently used with collections.

You can check if a type is of generic type using Type.IsGenericType property.


Benefits

Before generics, generalization in C# was achieved by casting types to and from Object type. But using generics you can assure type safety at compile time. 

With generics, you don't have to box unbox types as we used to do with ArrayList in .NET 1.0



Benefits of Generics

Generic type parameters ##

It is a placeholder for a specific type the client specifies when instantiating a generic type. 

Generic Classes
Encapsulate operations that are not specific to a single data type. Are commonly used with collection classes. 

Difference between Generic type and Generic type definition
  • Generic type definition : List<T>
    • T is called Generic Type Parameter
  •  Generic type : List<string> 
Constraints on generic type
https://msdn.microsoft.com/en-us/library/d5x73970.aspx

System.Collections.Generic namespace

Contains useful generic collections. 
  • Dictionary
  • LinkedList
  • List




Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook