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.