Oct 26, 2012

RESTful Service

1. Uses HTTP as a communication protocol for remote interactions.

2. Rather than singular service endpoint, we have many individual resource/URIs. So its resource oriented architecture.

3. URIs (resources) supports multiple HTTP verbs (GET,PUT,POST,DELETE,HEAD,OPTION) and HTTP response codes.

GET, HEAD, and OPTIONS - Safe methods that aren't intended to have side effects
GET,PUT,DELETE,HEAD,OPTION - Idempotent,can be repeated multiple times without harm.
POST - Server define actual function, cannot be considered safe/idempotent by clients.

Refer to following specification for detail of HTTP Method RFC 2616 §9

HTTP defines a suite of standard response codes that specify the result of processing the request.
Successful 2xx
Redirection 3xx
Client Error 4xx
Server Error 5xx

The HTTP specification also defines a suite of headers that can be used to negotiate behavior between HTTP clients and servers. These headers provide built-in solutions for important communication concepts like redirection, content negotiation, security (authentication and authorization), caching, and compression.

Few Examples

GET http://<host>/ExploringMvc/api/Product?id=1 HTTP/1.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Cache-Control: private, max-age=60, s-maxage=0
Content-Length: 3495
Content-Type: text/html; charset=utf-8
Content-Type: application/json; charset=utf-8
Date: Mon, 29 Oct 2012 00:42:54 GMT
Expires: Thu, 01 Dec 1994 16:00:00 GMT
ETag: 792373472
Last-Modified: Mon, 29 Oct 2012 00:55:44 GMT
If-Match: "xyzzy"
If-Modified-Since: Mon, 31 Oct 2012 00:42:54 GMT

Refer to following specification for detail of HTTP Header RFC 2616 §14

Resource can support multiple media type which can be negotiated between client/server.

4. Response contains number of hypermedia controls for different things to do next. This allows the server to change its URI scheme without breaking clients. The reason it’s called the “Web” is because resources can contain hyperlinks  to other resources, thereby creating a Web of resources.

From RPC-style to RESTful
Unlike RPC-style, you no longer focus on designing methods. Instead, you focus on the resources that make up your system, their URIs, and their representations and then you decide which of HTTP Verb you’ll support for each resource. So you short of move from Verbs to Nouns. If I am designing RPC-style service my focus will be on following operations
GetProductList()
GetProduct(int id)
AddProduct(Product product)
DeleteProduct(int id)
UpdateProduct(Product product)

If you notice that all above operations is for Product resource. So moving from RPC-style to RESTful, my focus will shift to Product resource. And then I will decide which of HTTP Verbs I need to support.

In RPC, Contract is service description document. All of service endpoint,operation, data type argument return, exception are defined in self contained application protocol defination

In REST,

  • contract is uniform interface.Action/Error semantics are specified by uniform interface.
  • Input and output are tied to media type specification.
  • State transitions are specified by hype mdeia
  • no service/operation, only resources and standard control data element such as http verb
  • no data type, no argument, no return value, they are simply media type, which are sequence of bytes from view point of uniform interface.
  • in rest hyper media driven workflow enable relationship between client/server to be much more dynamic in the sense that component can be moved around like resources can be added without breaking client.
  • generating proxy is not simple as in case of REST
  • in a truly RESTful architecture, the concept of statelessness implies that all relevant application states must be supplied with each and every request.By relevant, it is meant that whatever is required by the REST API to process the request and serve an appropriate response.


Reference:
http://martinfowler.com/articles/richardsonMaturityModel.html
http://www.w3.org/Protocols/rfc2616/rfc2616.html

Oct 19, 2012

ASP.NET Web API Intoduction


ASP.NET Web API is framework built on top of ASP.NET, for building RESTful applications on .NET Platform. These are intended to return data in the form of JSON/XML etc  rather than HTML markup. This can be used to create HTTP services that only use the standard HTTP concepts (URIs and verbs), and to to create services that use more advanced HTTP features – request/response headers, hypermedia concepts etc.

Some Key features
. Support for MVC style URL routing
. Content Negotiation based on Accept headers (Content-Type: application/json or xml etc) for request and response serialization.
. Easily extensible Formatter, default is JSON.NET. Refer to http://json.codeplex.com/ for feature comparison
. MVC style convention-over-configuration
. Easily extensible similar to MVC
. Testable using testing concepts similar to MVC
. Parameter binding(using model binding and formatter)
. This framework borrows a lot of concepts from ASP.NET MVC.


With earlier version of Mvc there is an option of calling Controller.Json Method, which creates a JsonResult object that serializes the specified object to JSON format. Also there is an option of writting custome Xml Action result and similarly for any other format. But this doesn't provide a  way to automatically negotiate content types and serve various content formats directly.

Other option is WCF service with the use of webHttpBinding. In spite of complicated configuration, I like this framework specially for the reason this is designed for transport independent. This bring to an important point in choosing between WCF and ASP.NET Web API. If you need service which need to support multiple transport protocol, Wcf is a way to go, but if you are designing service only for HTTP, then Web API could be a better option as it has less complicated configuration, little simpler in terms of use of attributes (for specifying verb,Uri) and support for testing as this was an important goal throughout the design and development around ASP.NET MVC. Also WCF was primarily designed for SOAP-based XML messages. I ran into few problems in past around this as example I was having operation which was throwing FaultException (System.ServiceModel). This works great as long as I was using this for SOAP but when I started using the same service for end point with webHttpBinding, I was not getting desired behaviour. Later on I realised that for this to work nicely with webHttpBinding I need to throw WebFaultException(System.ServiceModel.Web). So I finally moved this error handling as a part of endpoint behaviour to make my serivce transport independent. Refer to my WCF blog on detail solution.

Using raw HTTP Handlers and Modules in the core ASP.NET runtime is also one option but you have to do pretty much every thing by hand.

Web API is similar to MVC but not the Same. Coming with mind set of ASP.NET Mvc I struggled a lot for following difference. I am still not sure why there is difference in behavior.
. You cannot have two action parameters to be bind from body. Similar to ASP.NET Mvc I was expecting this to work. Refer to my blog on parameter binding for detail on this.
. ActionFilter are designed differently. API uses System.Web.Http.Filters.ActionFilterAttribute where as MVC uses System.Web.Mvc.ActionFilterAttribute. This means if you implement an MVC ActionFilter and you want that same functionality in your Web API you'll end up creating the filter twice.

Oct 18, 2012

Web API-My First Look At Parameter Binding


This takes http request and convert it into .Net type which is passed as action parameter. Without this every action would have to take request message and manually extract parameter.

WebAPI uses model binding (same as MVC ValueProviders) to read from the query string and Formatters to read from the body. Formatters gets the list of formatters from the HttpConfiguration, and then uses the request’s content-type to select an appropriate formatter. WebAPI has some default formatters-JSON.Net.

Following code show few configuration which can be done around JsonFormatter
//config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; //Use this for DataContractJsonSerializer
config.Formatters.JsonFormatter.Indent = true;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();

If the parameter has no attribute on it, then the decision is made purely on the parameter’s .NET type. Simple types uses model binding. Complex types uses the formatters.

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once. This means if formatter uses this for binding model, then you cannot access request content (Request.Content) inside action. This also means you cannot have two action parameters to be binded from body. Something like this will throw exception as "Can't bind multiple parameters ('body' and 'body1') to the request's content.",

public HttpResponseMessage PostProduct([FromBody] string body, [FromBody] string body1)

This behavior is different than Mcv, in which case model binding can repeatedly search through value providers.


Oct 15, 2012

Form Authentication(FormsAuthenticationModule)


Forms authentication cookie contains forms authentication ticket which is passed with each request. In case of cookieless forms authentication, the ticket will be passed in the URL in an encrypted format.

The ticket is encrypted and signed using the <machineKey> configuration element of the server's Machine.config file. If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively.

The authentication ticket contains various bits of information, such as the user name, the issue and expiry dates and user data.

Forms authentication tickets can be generated manually by using the FormsAuthenticationTicket class.

FormsAuthentication cookie name is .ASPXAUTH which is by default set and send to the browser once user is authenticated.

.ASPXAUTH=095F6C2AF0126AF84BD5A30AD2866328E06F61755EA6FCDEDAA5A79F9039FB38AC4812628A42C700B7E927B58CA6B50F831DA2143A06385AA422ED313CB39303C3C0DA75DCFE9BCF363B7969FCFC6B0114D362CE6C1A04C424C7B1D46A440170B1DABD47E6DD8C91D6EE64B74F5224B6


In case of non-persistent cookie, if the ticket is expired, cookie will also expire, and the user will be redirected to the logon page. If the ticket is marked as persistent, where the cookie is stored on the client box, browsers can use the same authentication cookie to log on to the Web site any time. FormsAuthentication.SignOut removes the forms-authentication ticket information from the cookie or the URL if CookiesSupported is false.


Aug 24, 2012

IIS overview


WWW Service
In IIS 7 and above, the WWW service no longer manages worker processes. Instead, the WWW Service is the listener adapter for the HTTP listener, HTTP.sys. As the listener adapter, the WWW Service is primarily responsible for configuring HTTP.sys, updating HTTP.sys when configuration changes, and notifying WAS when a request enters the request queue.

Additionally, the WWW Service continues to collect the counters for Web sites. Because performance counters remain part of the WWW Service, they are HTTP specific and do not apply to WAS.

Worker Processes
In IIS 7 and above, Windows Process Activation Service (WAS) manages application pool configuration and worker processes instead of the WWW Service. Each Web site runs in an application pool, which is a named worker process and logical memory allocation where one or more Web sites or applications reside. Each app pool runs in the W3wp.exe process.

Additionally, you can run WAS without the WWW Service if you do not need HTTP functionality. For example, you can manage a Web service through a WCF listener adapter, such as NetTcpActivator, without running the WWW Service if you do not need to listen for HTTP requests in HTTP.sys.

Following command can be used to list worker process

C:\Windows\System32\inetsrv>appcmd list wp

Modules
IIS include a Web server engine in which you can add or remove components, called modules, depending on your needs. Modules participates in the request processing of every request in order to change or add to it in some way.

Handler
A handler, is responsible for handling the request and producing the response for specific content types.

Jul 9, 2012

Xsl Transformation Custome ActionResult

In this post I am creating a custome action result which takes xml data and uses xsl to transform xml data to output page.

Our custome action result will be derived from abstract class ActionResult and need to implement abstract method ExecuteResult. ControllerActionInvoker calls ExecuteResult on the action result returned by the controller action.

In this method we first find the Xsl based on the ViewName and then transform xml using this xsl to generate response output

 public override void ExecuteResult(ControllerContext context)
 {
  if (context == null)
  {
   throw new ArgumentNullException("context");
  }

  if (string.IsNullOrEmpty(ViewName))
  {
   ViewName = context.RouteData.GetRequiredString("action");
  }

  XslCompiledTransform view = FindView(context, ViewName,true);
  
  var response = context.HttpContext.Response.Output;

  RenderView(response, view);
  
 }

Here are the helper method used for used for this.

Based on the viewName, I find view. I am using "~/Views/{1}/{0}.xsl" as ViewLocationFormat. If required more format can be used similar to View engine.

XslCompiledTransform is being cached for performance.


 private static XslCompiledTransform FindView(ControllerContext context, string viewName, bool useCache)
 {
  string controller = context.RouteData.Values["controller"].ToString();

  string keyPath = Path.Combine(controller, viewName);

  string virtualPath = string.Format("~/Views/{1}/{0}.xsl", viewName, controller);
  string viewPath = HttpContext.Current.Server.MapPath(virtualPath);

  // Try the cache           
  if (useCache)
  {
   ObjectCache cache = GetCache();

   if (cache[keyPath] == null)
   {
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load(viewPath);
    cache[keyPath] = xslt;    
   }

   return cache[keyPath] as XslCompiledTransform;
  }
  else
  {
   XslCompiledTransform xslt = new XslCompiledTransform();
   xslt.Load(viewPath);
   return xslt;
  }
 }
 
 private void RenderView(TextWriter response, XslCompiledTransform view)
 {
  response.Write(TransformXmltoHtml(PageData, view));
    }

May 24, 2012

Custom Controller Factory

Constructor Injection is the DI technique of passing an object's dependencies to its constructor. But this by default will not work with Mvc unless you have a parameterless constructor also defined. If you try to run, it will throw error stating that “No parameterless constructor is defined for this object”. A way to get around this and have DI is by defining both parameterless constructor as well as one with which you want to have dependency.

public class ProductController : Controller
    {
        #region Constructor
        
        public ProductController()
            : this(new ProductModel())
        {
        }

        public ProductController(IProductModel productModel)
        {
            if (productModel == null)
                throw new ArgumentNullException("productModel");
            ProductModel = productModel;
        }

        private IProductModel ProductModel { get; set; } 

        #endregion

The other way to achieve this is by defining CustomeControllerFactoryWithoutDefaultConstructor something like this

public class CustomeControllerFactoryWithoutDefaultConstructor : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return Activator.CreateInstance(controllerType, new ProductModel()) as IController;
        }
    }

And then register this in Global.asax:

ControllerBuilder.Current.SetControllerFactory(typeof(CustomeControllerFactoryWithoutDefaultConstructor));

Dependency Injection DI/IoC

Dependency Injection (DI) means that this is done without the object intervention. In other words the object dependency is on interfaces and not on concrete objects. This promotes greater reusability, easier maintainability, and mockability unit test. Thsi is also referred as Inversion of Control (IoC) which means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

Constructor Injection
Constructor Injection is the DI technique of passing an object's dependencies to its constructor.

 public class ProductController 
 {
  public ProductController(IProductModel productModel)
  {
   if (productModel == null)
    throw new ArgumentNullException("productModel");
   ProductModel = productModel;
  }

From the above it is clear to the developer invoking the object, which dependencies need to be given to the ProductController object for proper execution.

Consider a case where you have lots of methods with no dependencies and you are adding a new method that does have a dependency on IProductModel. So one way is to change the constructor to use Constructor Injection, but this will require changes to all existing constructor calls. So alternatively, you could just add a new constructor that takes the dependency.

 public class ProductController 
 {
  public ProductController()
  {
  
  }
  public ProductController(IProductModel productModel)
  {
   if (productModel == null)
    throw new ArgumentNullException("productModel");
   ProductModel = productModel;
  }

Now some one can argure how does a developer easily know when to use one constructor over the other.

The other case is, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? "Setter Injection" is another DI technique that can be used in situations such as this.

Setter Injection
In this case dependencies are set onto public properties exposed by the object in need.

 public class ProductController 
 {
  public ProductController()
  {
  
  }
  
  public IProductModel ProductModel { get; set; } 

Few things to consider here
 . In this case it does not make very clear when dependency need to be create as in case of constructor Injection.
. Also note that in constructor Injection we an exception is thrown if the dependency is not set immediately, where as with Setter Injection, an exception isn't thrown until a method actually attempts to use the dependency.

Injectors
Now someone has to create the dependency. One of the approach is to use "DI controller". In the following Mvc example I have two constructors default and the other with parameter. The framework will use default constructor where as for unit testing one can use the one which has parameter so that it can be easily mockable.

 public class ProductController : Controller
    {
        #region Constructor
        //
        // GET: /Product/
        public ProductController()
            : this(new ProductModel())
        {
            TempDataProvider = new CustomeTempDataProvider();
        }

        public ProductController(IProductModel productModel)
        {
            if (productModel == null)
                throw new ArgumentNullException("productModel");
            ProductModel = productModel;
        }

        public IProductModel ProductModel { get; set; } 

Even if "controller" is not well defined if you see at a high level in any properly tiered architecture "controller" layer always exists. For example in ASP.NET, the code-behind page acts as a controller layer.

The other approach is to use DI Containers. There are some frameworks (Spring .NET, Windsore) which allows you to define dependency injections within an XML file.

Apr 27, 2012

Wcf Operation Invoker - IOperationInvoker

Operation invoker is the last element in the WCF runtime which is invoked before the service implementation is reached – it’s the invoker responsibility to actually call the service operation on behalf of the runtime. This can be used to implement caching logic for expensive operations.

public class CachingOperationInvoker : Attribute, IOperationBehavior,IOperationInvoker
{
 readonly IOperationInvoker _originalInvoker;
 readonly double _cacheDuration;

 public CachingOperationInvoker(IOperationInvoker originalInvoker, double cacheDuration)
 {
  _originalInvoker = originalInvoker;
  _cacheDuration = cacheDuration;
 } 
 
 public double SecondsToCache { get; set; }
 
 #region Implementation of IOperationInvoker

 public object Invoke(object instance, object[] inputs, out object[] outputs)
 {
  ObjectCache cache = GetCache();

  string cacheKey = CreateCacheKey(inputs);
  CachedResult cacheItem = cache[cacheKey] as CachedResult;
  if (cacheItem != null)
  {
   outputs = cacheItem.Outputs;
   return cacheItem.ReturnValue;
  }
  object result = _originalInvoker.Invoke(instance, inputs, out outputs);
  cacheItem = new CachedResult { ReturnValue = result, Outputs = outputs };
  cache.Add(cacheKey, cacheItem, DateTimeOffset.UtcNow.Add(TimeSpan.FromSeconds(_cacheDuration)));

  return result;
 }
 
 #endregion
 
 #region Implementation of IOperationBehavior
 
 public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
 {
  dispatchOperation.Invoker = new CachingOperationInvoker(dispatchOperation.Invoker, SecondsToCache);
 }
 
 #endregion
Now you can easily decorate your operation with the attribute
  
 [CachingOperationInvoker(SecondsToCache = 100)]
    Product GetProduct(int id); 

One thing I would like to point out here is that the caching is happening at the server level which will mean that it will go through the wcf pipeline, the saving which we are doing here is the actual operation call. The other approach to consider here would be to come up with caching logic at the client side. Unlike REST services, SOAP services don’t have any standard way of defining caching options for their operations.

Apr 10, 2012

Conditional Cache for RESTful service

As per the HTTP specification, GET and HEAD shouldn’t have any side effects that would adversely effect the caching of the response, unless server prohibits caching. Most of the browser caches HTTP/200 responses, unless Expires, Pragma, or Cache-Control headers are present.

Just by having ETag or Last-Modified time, your GET method will be cached in the browser. You can easily test this using fiddler.

 In this post I am going to write a conditional cache logic based on ETag and/or LastModified. In the following code Product object has two additional fields : ETag and LastModifiedDate, based on this (both or eather) field, we will determine if we need to suppress Entity Body and accordingly set the response status to NotModified.

 
 public Product GetProductRestStyle(string id)
 {
  OutgoingWebResponseContext outgoingResponse = WebOperationContext.Current.OutgoingResponse;
  IncomingWebRequestContext incomingRequest = WebOperationContext.Current.IncomingRequest;

  //retrieve product object from any repository
  Product product = GetProduct(Convert.ToInt32(id));

  if(product == null)
  {
   outgoingResponse.SetStatusAsNotFound();
   return null;
  }

  //Product object contains LastModifiedDate and ETag, which we will compare in the incomingRequest 
  //and if it is same we will supress the response body
  CheckModifiedSince(incomingRequest, outgoingResponse, product.LastModifiedDate);
  CheckETag(incomingRequest, outgoingResponse, product.ETag);

  //Set LastModifiedDate and ETag on the outgoing response 
  outgoingResponse.ETag = product.ETag.ToString();
  outgoingResponse.LastModified = product.LastModifiedDate;

  //Give a cache hint
  //Resource will expire in 10 sec
  outgoingResponse.Headers.Add(HttpResponseHeader.CacheControl, "max-age=10");
  
  return product;
 }
 
 private static void CheckETag(IncomingWebRequestContext incomingRequest, OutgoingWebResponseContext outgoingResponse, Guid ServerETag)
 {
  string test = incomingRequest.Headers[HttpRequestHeader.IfNoneMatch];
  if (test == null)
   return;
  Guid? eTag = new Guid( test);
  if (eTag != ServerETag) return;
  outgoingResponse.SuppressEntityBody = true;
  outgoingResponse.StatusCode = HttpStatusCode.NotModified;
 }

 private static void CheckModifiedSince(IncomingWebRequestContext incomingRequest, OutgoingWebResponseContext outgoingResponse, DateTime serverModifiedDate)
 {
  DateTime modifiedSince = Convert.ToDateTime(incomingRequest.Headers[HttpRequestHeader.LastModified]);

  if (modifiedSince != serverModifiedDate) return;
  outgoingResponse.SuppressEntityBody = true;
  outgoingResponse.StatusCode = HttpStatusCode.NotModified;
  
 }


The above code will be useful in the following conditions:
In the case where the client cannot tolerate a stale cache and a "hint" is not good enough, they may issue a request to the server, if the cache is still fresh, the server will send a 304 "Not Modified" response with no entity body. The client can then safely source the data from it’s cache.

Another scenario is the case where the client abides by the caching hint, but the cache is expired. As opposed to simply throwing away the cache, the client can issue a Conditional GET to see if the cache is still good.

Mar 19, 2012

Wcf Message Inspector - IMessageInspector

You can use message inspector to log, inspect, modify or completely replace a message by implementing IClientMessageInspector (client side) or IDispatchMessageInspector (server side)
 #region IDispatchMessageInspector Implementation

 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
  //You can access the body of a Message only once, regardless of how it is accessed.
  //http://msdn.microsoft.com/en-us/library/ms734675.aspx
  request = LogMessage(request.CreateBufferedCopy(int.MaxValue));
  return null;
 }

 #endregion

 
Now this can be added through Endpoint/Service/Contract behavior
 
  public class LogMessageEndpointBehavior : Attribute, IEndpointBehavior
 {
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new LoggingMessageInspector());
        }

 }
 

Mar 1, 2012

WCF error handling using DataAnnotations Validator

ParameterInspector can also be used to validate DataMember in the data contract for the incoming request by using DataAnnotations Validator.

So suppose I have a DataContract defined something like this

 [DataContract]
    public class CompositeType
    {
        string stringValue = "Hello ";
        [DataMember]
        [Required(ErrorMessage = "Name is required")]
        [StringLength(20, MinimumLength = 1, ErrorMessage = "Name must have between 1 and 20 characters")]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

Refer to DataAnnotations Required and StringLength attribute. Now I want a generic Validator which inspects the parameter and does Validation using DataAnnotations.

 
 public class ValidatingParameterInspector : IParameterInspector
    {
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState){}
  
        public object BeforeCall(string operationName, object[] inputs)
        {
   //So I loop through all the input parameters and validate it using DataAnnotations Validator
            foreach (var input in inputs)
            {
                if (input != null)
                {
                    ValidationContext context = new ValidationContext(input, null, null);
                    Validator.ValidateObject(input, context, true);
                }
            }
            return null;
        }
    }
And now you can add this to OperationBehavior or even endpoint behavior
 

 public class ValidatingParameterInspectorOperationBehavior : Attribute, IOperationBehavior
    {
        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation){}
        public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters){}
        public void Validate(OperationDescription operationDescription){}
        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            ValidatingParameterInspector validatingParameterInspector = new ValidatingParameterInspector();
            dispatchOperation.ParameterInspectors.Add(validatingParameterInspector);
        }
    } 
So now before call reaches to the operation it will be inspected by BeforeCall where it will fail validation and raise exception. You can also raise custom FaultException

WCF error handling by implementing IErrorHandler

By implementing IErrorHandler you can control the fault message which is sent to the caller and perform error processing such as logging
  

 public class MyCustomeErrorHandler : IErrorHandler
    {

        public bool HandleError(Exception error)
        {
            Trace.TraceError(error.ToString());
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
   //Log server error for troubleshooting error
   
   //you can customise fault exception as you want
            FaultException faultException = new FaultException("Server error encountered.);
            MessageFault messageFault = faultException.CreateMessageFault();
            fault = Message.CreateMessage(version, messageFault, faultException.Action);
        }

    }
We can now add this to ServiceBehavior
  

 public class MyCustomeErrorHandlerServiceBehavior : Attribute,IServiceBehavior
    {
        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase){}

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters){}

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            IErrorHandler handler = new MyCustomeErrorHandler();
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(handler);
            }
        }
    }
 
Now this way your custome error handler will be used where you can put some friendly message which will be sent to the caller.

The other way is to catch your application error in your operation and then throw FaultException somethign like this
 

 public string GetData(int value)
 {
  try
  {
   throw new Exception("My Service Operation Error");
  }
  catch (Exception ex)
  {
   //Log your applocation exception
   throw new FaultException(new ApplicationException("My Custome Fault Messahe"),new FaultReason("some fault reason"));
  }
 }

Feb 28, 2012

jQuery Deferred object

You can create a Deferred object like this

var dfd = $.Deferred()

As of now this goes to the pending state (or unfulfilled)

you can add as many number of then(),done(),fail() which is kindof event. These are callbacks which are called once deferred object is resolved or rejected. So you can consider these as listener which can be triggered by calling resolve or reject.
 

  dfd.done(function(){
   alert("deferred object got resolved");
  })
  
  dfd.done(function(){
   alert("I am also notified that the deferred object got resolved");
  })
  
  dfd.fail(function(){
   alert("deferred object got rejected");
  })
  
  dfd.then(function(){
   alert("deferred object got resolved");
  },function(){
   alert("deferred object got rejected");
  }
  )

Once you resolve or reject deferred object it goes into resolved (fulfilled) or rejected (failed) state. When the Deferred is resolved, any doneCallbacks added by done or then are called in the order they were added. Similarly for reject, it call fail or fail part of then.
 
  dfd.resolve();
  dfd.reject();

State 
Deferred object has state which you can get from dfd.isResolved() or dfd.isRejected(). The state is persistent, which means once resolved or rejected it will maintain its state forever. After this any then/done/fail called will be executed immediately.

Promise
This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe. isResolved, and isRejected) to prevent users from changing the state of the Deferred.

dfd.promise();

If you return deferred object it gives the caller access to resolve or reject directly. So if you don't want caller to have that access then you can return promise object.

Real word example

1. jQuery ajax has been implement using deferred. Now when you do $.get("jQuery-Deferred.html"); it returns Promise object which is read only (It exposes only the Deferred methods needed to attach additional handlers or determine the state, but not ones that change the state )
 
  var req = $.get("jQuery-Deferred.html");
  req.done(function( response ){
     alert("ajax call done");
   });
  req.fail(function( response ){
     alert("ajax call failed");
   }); 

2. Convenient Wait function
 
 function timedMsg()
 {
  wait(1).done(function(){alert("I am displaying after 1 second");});
  wait(11).fail(function(msg){alert(msg);});
 }

 function wait(time) 
 {
  var dfd = $.Deferred();
  if(time < 10){
   setTimeout(dfd.resolve,time*1000);
  }
  else
  {
   dfd.reject("User will not like more than 10 second of wait time.");
  }
  //By returning promise I make sure that the caller doesn't have ability to reject or resolve.
  return dfd.promise();
 }


3. Efficient ajax call
 
 function someCostlyTaskLikeAjax(url) 
 {
  alert("someCostlyTask is called");
  var time = 1;
  var dfd = $.Deferred();
  setTimeout(dfd.resolve("I am resolved"),time*1000);
  return dfd.promise();
 }
 
 function cachingDeferredObject(){
  
  var cache = {};
  
  function fetch_some_object(key){
   if (cache[key]) { 
    alert("I am coming from cache - " + cache[key]);
    return cache[key]; 
    }
    
   return cache[key] = someCostlyTaskLikeAjax(key).done(function(msg){
    //cache = msg;
    alert("From done handler -" + msg);
    return msg;
   });
  }
  
  $.when(fetch_some_object("someurl")).done(function(a){
   alert("1St call - " + a);
  })
  
  $.when(fetch_some_object("someurl")).done(function(a){
   alert("2nd call -" + a);
  })
  
 }

Feb 24, 2012

Wcf parameter inspector - IParameterInspector

The parameter inspector is a way of intercepting requests / responses after all the processing of extracting parameters from incoming messages (or before they’re packaged in outgoing messages) is done. Before and after each call, the inspector gets a chance to inspect the operation inputs, outputs and return value, in the same types as defined by the operation contract. There is no conversion required, you just need to cast it to the desired type, since the parameters are passed as objects.

This can be done by implementiong IParameterInspector which has only two methods:
1. public object BeforeCall(string operationName, object[] inputs)
2. public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)

Real world scenario
1. Some common validation which need to be done for large number of operations. For example name field which accepts only [a-zA-Z]. It would't be hard to implement this in the method (operation) itself, but if you need to do this for lot of cases then it might make sense to implement the validation logic as an IParameterInspector extension that can be declaratively applied to any operation.

2. To capture performance timing. The parameter inspector interface methods are called really close to the actual method invocation both on the client and on the server, so the time difference between before and after call can be calculated as operation duration.
  

 class NameValidationParameterInspector : IParameterInspector
    {
        readonly int _nameParamIndex;
        const string NameFormat ="[a-zA-Z]";
  
        public NameValidationParameterInspector() : this(0) { }

        public NameValidationParameterInspector(int nameParamIndex)
        {
            _nameParamIndex = nameParamIndex;
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
   //Access the parameter. you need to know the index of the parameter. In this case we will always validate the 
   //first parameter which is being passed
            string nameParam = inputs[_nameParamIndex] as string;

            if (nameParam != null)
                if (!Regex.IsMatch(
                    nameParam, NameFormat, RegexOptions.None))
                    throw new FaultException(
                        "Invalid name. Only alphabetical character");
            return null;
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState){}
    }
And now add this to behavior
 

 public class NameValidationOperationBehavior : Attribute, IOperationBehavior
    {
        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
            NameValidationParameterInspector nameValidationParameterInspector = new NameValidationParameterInspector();
            clientOperation.ParameterInspectors.Add(nameValidationParameterInspector);
        }

        public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters){}
  
        public void Validate(OperationDescription operationDescription){}

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            NameValidationParameterInspector nameValidationParameterInspector = new NameValidationParameterInspector();
            dispatchOperation.ParameterInspectors.Add(nameValidationParameterInspector);
        }
    }
And now you can decorate any operation with attribute NameValidationOperationBehavior.
In this example I calculate the operation time
 
 public class OperationProfilerParameterInspector : IParameterInspector
    {
        public object BeforeCall(string operationName, object[] inputs)
        {
                return DateTime.Now;
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            DateTime endCall = DateTime.Now;
            DateTime startCall = (DateTime)correlationState;
            TimeSpan operationDuration = endCall.Subtract(startCall);
        }
    }
And now add to the EndpointBehavior
 
 public class OperationProfilerEndpointBehavior : IEndpointBehavior
    {
        public void Validate(ServiceEndpoint endpoint){}
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters){}
  
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations)
            {
                operation.ParameterInspectors.Add(new OperationProfilerParameterInspector());
            }
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            foreach (ClientOperation operation in clientRuntime.Operations)
            {
                operation.ParameterInspectors.Add(new OperationProfilerParameterInspector());
            }
        }
    }

    public class OperationProfilerBehaviorExtensionElement : BehaviorExtensionElement
    {
        protected override object CreateBehavior()
        {
            return new OperationProfilerEndpointBehavior();
        }

        public override Type BehaviorType
        {
            get { return typeof(OperationProfilerEndpointBehavior); }
        }
    }
configuration change for the new behavior
 
 
  
    
   
    
  
    
    
    
      
        
          
          
          
          
        
      

      
        
          
        
      
    

    
      
        
      
    
   
    
  
The same can be done at the client side.
    Service1Client client = new Service1Client();
    client.Endpoint.Behaviors.Add(new     OperationProfilerEndpointBehavior());

or in configuration like this


        
          
        
      
      
        
          
            
          
        

      

            
        

Feb 23, 2012

Wcf Moving Pieces

Service Contracts and Dispatch Behavior

Service contract is a traditional C# interface. These interface are annotated with [ServiceContract] and each operation which you want to expose with [OperationContract]:
 [ServiceContract]
    interface IHelloWorldService
    {
        [OperationContract]
        string GetMessage(string name);

    }
These attributes are used for mapping between .net and SOAP for dispatching and serialization. Dispatching is the process of deciding which method to call for an incoming SOAP message. Serialization is the process of mapping between the data found in a SOAP message and the corresponding .NET objects used in the method invocation. This mapping is controlled by an operation's data contract.

WCF dispatches based on the message action which comes in the SOAP header. Each method in a service contract is automatically assigned an action value based on the service namespace and method name. Action value can be customized.

 [ServiceContract(Namespace="http://hello.com/IHelloWorldService/")]
    interface IHelloWorldService
    {
        [OperationContract(Action="MyCustomizedActionGetMessage")]
        string GetMessage(string name);

    }

Data Contracts
Once the target method has been determined based on the action, WCF relies on the method's data contract (types used in the method signature) to perform serialization. The way WCF serializes .NET classes depends on the serialization engine in use. The default serialization engine is known as DataContract. Message is a special type in which WCF does not perform type-based serialization. Instead, it just gives you direct access to what's found in the SOAP message. With DataContract, only fields marked with DataMember will be serialized.

 {DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

For more sophisticated you can always use XmlSerialize. WCF also supports serializing types marked with [Serializable].

svc file is a text file which contains the details required for WCF service to run it successfully.

With WCF, you're either writing services that expose endpoints or you're writing clients that interact with endpoints. Hence, endpoints are central to the WCF programming model and infrastructure. 



     (.Net Objects\Entities)          (WCF Message)
Client ------------------------------> Proxy ------------------------> Messaging Layer/Channel Stack
                                                                                                         | 
                                                                                                         | (Raw Message Data)
                                                                                                         |
                                                                                                        v
Service<-------------------------------Dispatcher<-------------------Messaging Layer/Channel Stack
        (.Net Objects\Entities)                (WCF Message)


Messaging
The messaging layer is composed of channels which processes a message. A set of channels is also known as a channel stack. There are two types of channels: transport channels and protocol channels.
Transport channels read and write messages from the network. Ex Http and Tcp
Protocol channels implement message processing protocols, often by reading or writing  additional headers to the message. Examples of such protocols include WS-Security and WS-Reliability.

  Client Side   Service Side

 Protocol Channel Protocol Channel
Protocol Channel Protocol Channel
Protocol Channel Protocol Channel
Message Encoder                          Message Encoder
TransportChannel------------------------------->TransportChannel
                            (Raw Message Data)



Proxy
The main responsibility of the proxy is to transform the caller-supplied objects (parameters) into a WCF Message object, which can then be supplied to the underlying channel stack for transmission on the wire.

        Method1()                                          Method2()
Parameter Inspection Parameter Inspection
| |
Message Formatting (serialization) Message Formatting (serialization)
| |
-----------------------------------------------------------
|
Message Inspector




Dispatcher

       Operation1()                                                   Operation2()
    Operation Invoker                                            Operation Invoker
|                                                                |
    Parameter Inspection                                      Parameter Inspection
|                                                                |
    Message Formatting (serialization)             Message Formatting (serialization)
|                                                                |
-------------------------------------------------
|
Operation Selector
|
Message Inspector




Endpoint  System.ServiceModel.ServiceEndpoint


Address   System.Uri

Binding    System.ServiceModel.Binding
In WCF, a binding determines how WCF is going to communicate. A binding is really the configuration that tells WCF how to build what is known as the channel stack, which is the set of objects that will work together to provide the type of communication you want for a particular endpoint.


Contract   Interfaces annotated with System.ServiceModel attributes


Feb 13, 2012

From Browser (request) to View (response) - Mvc Under the Hood

In Global.asax.cs we register routes something like this

protected void Application_Start()
 {
  AreaRegistration.RegisterAllAreas();

  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);
 }
 
 public static void RegisterRoutes(RouteCollection routes)
 {
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Employee", action = "CreateEmployee", id = UrlParameter.Optional } // Parameter defaults
  );

 }


routes.MapRoute is extension method defined in System.Web.Mvc.RouteCollectionExtensions.cs. When you decompile this you will notice that how a route with particular URL is being register and associated with MvcRouteHandler.

Route route = new Route(url, new MvcRouteHandler()) { 
  Defaults = new RouteValueDictionary(defaults), 
  Constraints = new RouteValueDictionary(constraints),
  DataTokens = new RouteValueDictionary() 
 };

There are bunch of default HttpModules and HttpHandlers in your IIS configuration. Just take a look here - %WINDOWS%\Microsoft.NET\Framework\v4.0.30319\Config\web.config.

and in the list of modules () notice UrlRoutingModule
Now decompile UrlRoutingModule and look at PostResolveRequestCache where it Matches the HTTP request to a route, retrieves the handler for that route, and sets the handler as the HTTP handler for the current request.

public virtual void PostResolveRequestCache(HttpContextBase context)
 {
  RouteData routeData = this.RouteCollection.GetRouteData(context);
  if (routeData == null)
  {
   return;
  }
  IRouteHandler routeHandler = routeData.RouteHandler;
  if (routeHandler == null)
  {
   throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0]));
  }
  if (routeHandler is StopRoutingHandler)
  {
   return;
  }
  RequestContext requestContext = new RequestContext(context, routeData);
  context.Request.RequestContext = requestContext;
  IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
  if (httpHandler == null)
  {
   throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[]
   {
    routeHandler.GetType()
   }));
  }
  if (!(httpHandler is UrlAuthFailureHandler))
  {
   context.RemapHandler(httpHandler);
   return;
  }
  if (FormsAuthenticationModule.FormsAuthRequired)
  {
   UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this);
   return;
  }
  throw new HttpException(401, SR.GetString("Assess_Denied_Description3"));
 }

This is how MvcRouteHandler(routeHandler.GetHttpHandler(requestContext)) is used for the Mvc application.  In case of aspx.net, all the handlers are listed in the web.config file, which are based on the file extension. You will noticed that there is non for mvc.

As requests move through the pipeline(modules) it find UrlRouting module (refer to web config). UrlRouting module matches incoming request URL with registered collections of Routes. For found matched Route it gets corresponding route handler (MvcRouteHandler). From routehandler (MvcRouteHandler) it gets the GetHttpHandler which in this case if MvcHandler.

Once the request comes to the MvcHandler.ProcessRequest, it creates controller from the controller factory (DefaultControllerFactory) and then call execute method on the controller which calls controller action.

Execute (member of IController which is implemented in ControllerBase)
   -> ExecuteCore (which is implemented in Controller)
         ->ControllerActionInvoker.InvokeAction
             ->GetParameterValues- This uses model binder to get the parameter value.
             -> Based on filter it calls filter.OnActionExecuting and finally call controller action.

At this point in the lifecycle, we’ve entered our application code. Your controller action return ActionResult.

             ->After view is executed it calls filter.OnActionExecuted
             ->ControllerActionInvoker.InvokeActionResult
                 ->ViewResultBase->ExecuteResult
                 ->FindView (which is implementation of IViewEngine). This returns ViewEngineResult                    which is an implementation of IView
                 ->This then call Render(member of IView) on the View and pass ViewData,tempdata and context.HttpContext.Response.Output writer so that View can process the data and write it to the output.



1. RouteConstraint
The URL Routing framework recognizes two different types of constraints. If you supply string for a constraint then the string is interpreted as a regular expression. The other option is to create a custom constraint by creating an instance of a class that implements the IRouteConstraint interface. Routing framework provides HttpMethodConstraint.

2. RouteHandler

3. ControllerFactory
Mvc handler gets the name of controller (Based on the route) and then uses controller factory (DefaultControllerFactory) to create an instance of controller. The default factory uses reflection to create an instance that implements IController and whose name ends with Controller.

DefaultControllerFactory uses the parameter-less constructor so if you want to use DI it will throw error stating that “No parameterless constructor is defined for this object”. This is one of the case where you can implement a custome controller factory by implementing DefaultControllerFactory and override GetControllerInstance.

4. ActionInvoker- This is the sequence of operation which happens here.

ControllerActionInvoker.InvokeAction
      InvokeAuthorizationFilters
      GetParameterValues
      InvokeActionMethodWithFilters
            OnActionExecuting
            InvokeActionMethod Returns ActionResult
            OnActionExecuted
      InvokeActionResultWithFilters 
            OnResultExecuting
            InvokeActionResult Calls ExecuteResult on ActionResult returned by InvokeActionMethod     
            OnResultExecuted 

5. ActionMethodSelectorAttribute
Actions, with the default action invoker, are selected based on their name.

One of the scenario for a custom selector attribute is if you want to choose action based on the browser like mobile browser or desktop browser.

6. AuthorizationFilter


7. ActionFilter
Action Filters are executed before and after an action is executed.

Filters can be used for many purpose like to extract data from session\httpcontext. This makes controller lighter and any component called from controller free from objects like session data\httpcontext. Having this encapsulated in filter makes it easily reusable across different controller action. The other places where I have used is to manage (set/get) http headers ( like If-Modified-Since and If-None-Match) specifically for Etag to support conditional caching. In short I consider this to be a place for anything which doesnot belongs to model.

8. ModelBinder
The default model binder maps HTTP parameters (by using value providers) to action method parameters using their names. 

For DefaultModelBinder you need to have parameter object with parameterless constructor. Also you cannot use interface type as a parameter. To extend the support for these types of parameter you can extend DefaultModelBinder. Also the other condition you might use it to convert the id of the person directly to the Person object looking up on the database, although I consider this kind of thing to belong to model.

9. ValueProvider
Value providers are used by the model binding system in MVC to populate the values of model objects. MVC 3.0 includes value providers for several common value sources
System.Web.Mvc.FormValueProviderFactory
System.Web.Mvc.HttpFileCollectionValueProviderFactory
System.Web.Mvc.QueryStringValueProviderFactory
System.Web.Mvc.RouteDataValueProviderFactory

For any other value provider like CookieValueProviderFactory we can implement ValueProviderFactory.

10. ControllerBase
All controllers inherit from the base class Controller. To encapsulate common logic or conventions you can have your own base calss which inherits from Controllers. You can also apply filter to this base.

11. ResultFilter
Like action filter result filters are executed before and after action result is executed. ActionFilterAttribute implements both IActionFilter, IResultFilter.

Logging/Output caching from action result can be done at this level.

12. ActionResult
ASP.NET MVC comes with many different kind of results to render views, to render JSON, plain text, files and to redirect to other actions.

You can implement this in case of any specific type of requirement. One of the example where I have tried this is to write Xsl Transformation ActionResult where I pass xml object (same as view model) and based on the action it uses xsl file to transform xml object to output page.

13. ViewEngine
Example Razor(cshtml) and ASPX/WebForm view

One of the example where I create a MobileCapableRazorViewEngine by deriving it from RazorViewEngine and overriding FindView to specify view name based on the browser from where the request is coming.

14. HtmlHelper
HtmlHelper is just an extension method of the HtmlHelper class.Views must be very dumb and thin, and they should only have html markup and calls to HtmlHelpers. Writting helpers come very handy for extracting the code from the view and putting it into something that is testable\reusable.

15. TempDataProvider
Life span of TempData object is only till the subsequent request, or until the item is removed explicitly. This is useful when you want to pass data to another view that you will be redirecting to, rather than rendering to. By default, TempData is stored in the session using SessionStateTempDataProvider.

CustomeTempDataProvider just need to implement ITempDataProvider which has method SaveTempData where you can put your logic for storing this wherever you want.

Jan 18, 2012

Mobile Capable View Engine- Custome View Engine

One of the nice feature of ASP .NET MVC framework is its Extensibility. I created a custom view engine which changes view location based on the device from where its being accessed.

In the following code I update view name with mobile specif view, if the request is being originating from mobile devise

 public class MobileCapableRazorViewEngine : RazorViewEngine
    {
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if(IsMobileDevice(controllerContext))
   {
    viewName = viewName + ".mobile";
    masterName = masterName + ".mobile"
   }
        }
 }
 
 private static bool IsMobileDevice(ControllerContext controllerContext)
 {
  //ASP.NET’s built-in browser detection support may not be sufficient for all applications specifically in case of latest devices
  //add the open source 51Degrees.mobi Foundation library to your project
  //you can also use UserAgent controllerContext.HttpContext.Request.UserAgent
  return controllerContext.HttpContext.Request.Browser.IsMobileDevice;
 }


And in the global.asax remove the default view engine and add our custome view engine.

 //Remove default RazorViewEngine and add MobileCapableRazorViewEngine
 ViewEngines.Engines.Remove(ViewEngines.Engines.OfType().First());
 ViewEngines.Engines.Add(new MobileCapableRazorViewEngine());

 

Similar approach can be taken for FindPartialView.

Jan 17, 2012

Pipe and Filters

Break large transformation into small transform which lowers the complexity of individual transform. It also increases their potential for reuse.

Filter

A filter takes a message from its input, applies a transformation, and sends the transformed message as output. Filters implement simple transformation or transfer functions to  perform operations such as: Conversion, enrichment, filtering, batching, or consolidation.

Pipes
Pipes transport and buffer (data integrity/synchronization) messages between filters.

Key Points
1.The single-filter configuration implements the transformation by using one specialized component. The one hop that exists between input and output and the elimination of the interfilter communication translate into low latency and overhead.
2. The key tradeoffs in choosing between a combination of generic filters and a single specialized filter are reusability and performance.
3. Filters must not be dependent on other filters.

Simple Implementation

public interface IFilter
    {
        T Execute(T input);
    }

    public class Pipeline
    {
        private readonly List< IFilter> _filters = new List< IFilter>();

        public void Register(IFilter filter)
        {
            _filters.Add(filter);
        }

        public T Execute(T input)
        {
            T current = input;

            try
            {
                foreach (IFilter filter in _filters)
                {
                    current = filter.Execute(current);
                }
            }
            catch (Exception exception)
            {
                //Add error handling logic
                EventLog.WriteEntry(GetType().FullName,exception.Message);
                throw;
            }
            return current;
        }
    }

public class LowerCaseString : Filter1BaseClass,IFilter
    {
        protected override string Process(string input)
        {
            return input.ToLower();
        }
    }

    public class UpperCaseString : Filter1BaseClass,IFilter
    {
        protected override string Process(string input)
        {
            return input.ToUpper();
        }
    }

var input = "Test";
 Console.WriteLine("Input: {0}", input);
 Pipeline pipeline = new Pipeline();
 pipeline.Register(new LowerCaseString());
 pipeline.Register(new UpperCaseString());
 string output = pipeline.Execute(input);
 Console.WriteLine("Output: {0}", output);