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