Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

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

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 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