Tuesday, May 27, 2014

JQuery Interview question and answer with Practices: Part 3

clip_image001

Kindly visit first part of JQuery interview questions and answer.

jQuery Interview Question and Answers With Practices: Part 1

jQuery Interview Questions and Answers With Practices: Part 2

clip_image003 Differences Between jQuery .bind() vs .live() vs .delegate()?

clip_image005 .bind()

This is the most straight forward binding method. jQuery scans the document for all $('a') elements and binds the alert function to each of their click events.

This is the code segment which I am about to use in my example as shown below in image.

clip_image007

I’ve bind the click event on selector.

clip_image009

Whenever you click on any anchor link it prompts you the message as shown below.

clip_image011

The bind() method registers the type of event and an event handler directly to the DOM elements. This method basically searches for all the elements and binds the same handler to all the matches found.it doesn’t give you problem if matched elements are less however if there are plenty of matched elements than it raises some efficiency issue to attach(bind) event handler to all matched elements. It doesn't work for elements added dynamically that matches the same selector, because when bind scans the DOM tree the element must be present in the tree otherwise the handler will not be applied.

After clicking on each link it adds new link .To verify whether bind() works as expected on new added element, please click on that element.

Kindly refer the images below:

clip_image013

clip_image014

Note: if you click on the newly added link it doesn’t prompt you alert message.

.live()

jQuery binds the alert function to the $(document) element, along with 'click' and 'a' as parameters. Any time an event bubbles up to the document node, it checks to see if the event was a click and if the target element of that event matches the 'a'  selector. If both are true, the function executes.

The good thing about this code as compared to the .bind() example above is that it is only attaching the event handler once to the document instead of multiple times. This not only is faster, but less wasteful. It also attaches the event to dynamically added elements. Because the real information was registered on the document.it also doesn’t support chaining.

After clicking on each link it adds a new link dynamically, which prompts you alert.

A quick example of adding elements at runtime with an example shown below:

clip_image016

clip_image017

Note: if you click on the newly added link it prompts you alert message.

.delegate()

This function works in similar manner to live() function but instead of attaching event/selector information to document ,you can attach to element you desire.

Ref: http://api.jquery.com/delegate/

.delegate( selector, eventType, handler )Returns: jQuery

Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

· Delegates is faster/efficient than the live function because delegate is attached to specific root element rather than the document along with the selector/event information.

· You have the option of choosing where to attach the selector/event information.

· Chaining is better than live().

· Note: Chaining is not possible in live().

Below is the very descriptive image of delegates function and related terminology.

 

clip_image019

 

Note: if you click on the newly added link it prompts you alert message.

 

clip_image020

Note: on() is a replacement of all above method introduced in jQuery 1.7.1 version.in short I’d say it’s an integration of all above method.

clip_image021 What is event handler?

clip_image022I’ve used a term event handler mostly in above detailed description so I thought to lit on this also. “An Event handler is a code segment attached to an element which executes, when an event occurs on that element”.

Kindly have a look on shown below image:

clip_image023

clip_image003[1] Difference between Filter and Find?

clip_image005[1]As far as my understanding with these both perform action in similar way.

But filter searches all elements on basis of selector value, though find applies on child elements only.

Kindly have a look on a very descriptive image as shown below:

clip_image025

Hope you enjoyed this demonstration.

ThanksSmile

Keep coding and Smile Smile

Friday, May 23, 2014

jQuery Interview Questions and Answers With Practices: Part 2

Kindly visit the first part of the jQuery interview questions and answers.

Interview question and answer
jQuery Interview Question and Answers With Practices: Part 1


Question What are selectors in jQuery?

AnswerjQuery is one of the main features of jQuery. Because until we won't fetch elements from the DOM we are unable to perform further actions.

  • jQuery Selectors are used to select one or a group of HTML elements from your web page.
  • jQuery selectors always start with a dollar sign and parentheses: $()

There are some ways to select the elements in a web document.

1. Select elements by tag name

Example: $(div)

It will select all the div elements in the document.
2. Select elements by ID

Example: $(“#div1”)

It will select a single element that has an ID of div1.
3. Select elements by class

Example: $(“.even”)

It will select all the elements having a class even as shown in sample applications also.
An example of basic selectors are as shown in the following image:

selectors
There are some more selectors that are listed below and very useful from a jQuery perspective.

  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
  • $("ul li:first"): This selector gets only the first <li> element of the <ul>.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by <p> that have no children.
  • $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
  • $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
  • [attr] has attributes like type, value, href and id.
  • [attr=val] has attribute with value val.
  • [attr!=val] does not have attribute with value val.
  • [attr^=val] attribute begins with val.
  • [attr$=val] attribute ends with val.
  • [attr*=val] attribute includes val.
  • [attr~=val] attribute includes val as a word.
  • [attr|=val] attribute begins with val and optional hyphen.

Question What is jQuery.holdReady() function?

Answer By using the jQuery.holdReady() function we can hold or release the execution of jQuery's ready event. This method should be called before we run the ready event. To delay the ready event, we need to call jQuery.holdReady(true);

When we want to release the ready event then we need to call jQuery.holdReady(false);

This function is helpful when we want to load any jQuery plugins before the execution of the ready event or want to perform certain events/functions before document.ready() loads. For example some information also.

For example:

holdReady
Question What is chaining in jQuery?

Answer Chaining is a very powerful feature of jQuery. Chaining means specifying multiple functions and/or selectors to an element.
Chaining reduces the code segment and keeps it very clean and easy to understand. Generaly chaining uses the jQuery built in functions that makes compilation a bit faster.
By using chaining we can write the code above as follows:

$(document).ready(function () {

         $("#div2").html($("#txtBox").prop("readonly")) + '</br>';
         $("#div3").html($("#txtBox").attr("readonly"));
});

The code segment above is described by the image below:

chaining
Question What are the fastest selectors in jQuery?

Answer ID and element selectors are the fastest selectors in jQuery.

Question What are the slow selectors in jQuery?
Answer Class selectors are slow compared to ID and element.
Question How jQuery selectors are executed?
Answer Your last selectors are always executed first. For example, in the following jQuery code, jQuery will first find all the elements with class ".list" and then it will select all the elements with the id "li#first-li".

$('p').html($("li#first-li.list").text());
jQuery selectors executed

Question Which is the fastest, document.getElementByID('txtName') or $('#txtName').?
Answer Native JavaScipt is always fast. The jQuery method to select txtName "$('#txtName')" will internally make a call to document.getElementByID('txtName'). Since jQuery is written on top of JavaScript and it internally uses JavaScript only, JavaScript is always fast.

 

Keep coding and smile Smile

Monday, May 12, 2014

How MediaTypeFormatter and MediaTypeMapping Are Associated With Each Other in Web Api

 

Hi Techies

The Default Content Negotiation Algorithm is shipped as part of ASP.NET MVC4 WebAPI. The WebApi provides many nice features with which you can build Restful services. Conneg provides you MediaTypeFormatter and MediaTypeMapping.
If a Request message is sent with an Accept header then the Conneg algorithm will use the Accept header to decide about the Response media type and the MediaTypeFormatter to write. Here the client is asking for a response in a specific format.
If a Request message is sent with no Accept header and with a Content-Type header (let's say when you are using POST to post content to the server), the Conneg algorithm will use the Content-Type header to decide about the Response media type and the MediaTypeFormatter to write.
Here the Conneg algorithm uses its best approach to evaluate the format the client could understand. Since here the client was able to post content in a specific format like application/text, the Conneg algorithm decides that the Client could probably understand the Response also in the same format application/text.
There are the following four out-of-box MediaTypeFormatters that takes care of all these requests:

  1. JsonMediaTypeFormatter
  2. XmlMediaTypeFormatter
  3. FormUrlEncodedMediaTypeFormatter
  4. JQueryMvcFormUrlEncodedFormatter

There is one more way by which the Conneg algorithm decides about the Response's media type and formatter. It is called MediaTypeMapping. Every MediaTypeFormatter has a collection of these mappings in it.
By default, ASP.NET MVC4 Web API ships with the following 4 built-in media type mappings:

  1. QueryStringMapping
  2. RequestHeaderMapping
  3. UriPathExtensionMapping
  4. MediaRangeMapping

MediaTypeMapping allows you to write custom logic that fulfills the request. Fullfill the request means that a MediaTypeMapping has some value that exists in the request sent by the client that matches (like some value in the header). If it matches the request then it informs Conneg that a MediaTypeFormatter with the mediaType is ready to write and response.MediaTypeMapping provides full power to you to inspect the incoming request and make a decision of whether to participate in a response or not.
This is how both partcipate. In a subsequent article I'll explore MediaTypeFormatter.
What is the Precedence order of incoming request in WebApi handled by Conneg algo?
A definite question occurs when you work with the WebApi of how Conneg handles the request each time when multiple formatters match the request .There are certain ways like the Request Accept header, Content-Type header, MediaTypeMapping and so on that are considered by the Conneg to writing the response The Conneg algorithm must choose only one formatter in the end.
The Default Conneg algorithm has the following precedence order to select the final formatter:

  1. Formatter match based on Media Type Mapping.
  2. Formatter match based on Request Accept header's media type.
  3. Formatter match based on Request Content-Type header's media type.
  4. Formatter match based on if it can serialize the response data's Type.
  5. You can also use HttpResponseMessage to send the response despite of the Conneg algorithm overwrite it irrespective of the Request's Accept header media type.

 

Thanks

Sachin Kalia

Keep coding and smile

Friday, May 9, 2014

Precedence order of incoming request in web api handled by Conneg

 

web-api-sample-diagram

Hi Geeks

A definite question skrikes in mind when you work with WebAPI that how Conneg handles the request each time when multiple formatters match the request.

There are certain ways like the Request Accept header, Content-Type header, MediaTypeMapping etc .which consider by the conneg to writing the response

The Conneg algorithm has to choose only one formatter in the end.

The Default Conneg algorithm has the following precedence order to select the final formatter:

1. Formatter match based on Media Type Mapping.

2. Formatter match based on Request Accept header's media type.

3. Formatter match based on Request Content-Type header's media type.

4. Formatter match based on if it can serialize the response data’s Type.

5. You can also use HttpResponseMessage to send the resposne despite of the Conneg algorithm overwrite it irrespective of the Request’s Accept header media type.

Thanks

Cheers .Net Smile

Sachin Kalia

Wednesday, May 7, 2014

Factory Pattern in .Net with an example

Factory Pattern in .Net with an example
During my learning of design patterns, I came to know most frequent term Factory Pattern. I searched the Internet and came across numerous learning points. After a lot of search and study, I observed that to find the definition of Factory pattern.
In this article I try to explore this pattern in an easiest way with a very interesting topic Mobile.
An important aspect of software design is the manner in which objects are created. Thus, it is not only important what an object does or what it models, but also in what manner it was created.
At very first stage of an object creation is using “new” keyword, such a basic mechanism of object creation could result in design problems or added complexity to the design. On each Object creation we have to use new keyword. Factory helps you to reduce this practice and use the common interface to create an object.

Factory Pattern Definition

GOF says: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
The Factory Pattern is a Creational Pattern that simplifies object creation. You need not worry about the object creation; you just need to supply an appropriate parameter and factory to give you a product as needed.
· Creating objects without exposing the instantiation logic to client
· Referring to the newly created objects through a common interface
One of the most traditional designs of Factory Pattern is depicted below:
clip_image001
Let’s Move further and take a very general example for this situation. Which is about to get the Mobile details, wherein a customer may wish to get details of different kinds of mobile and their OS types. An illustrative image is depict below:
clip_image003
A mobile detail provides three different types of mobiles (Samsung, Apple and Nokia). Based on the client choice, an application provides the details of specific mobile. The easiest way to get the details is, client applications will instantiate the desired class by directly using the new keyword.
However It shows the tight coupling between Client and the Mobile class. Client application has to be aware of all the concrete Mobiles (Samsung, Apple and Nokia) and their instantiation logic. This methodology often introduces a great deal of the rigidity in the system. Also the coupling introduced between classes is extremely difficult to overcome if the requirements change on frequent interval.
Factory does the same work in bit different manner to create an object. Which is not visible to client? How Factory overcome on these fall backs by delegating the task of object creation to a factory-class (e.g. FactoryClass.cs) in our sample. The factory-class completely abstracts the creation and initialization of the product from the client-application. It helps to the client application to keep away from Object creation and the concrete details of mobile.
A typical image of a Factory pattern is depicted below to understand the fact.
clip_image004
The above given images simply tells the association of Client app with Factory class and the creation of object Via Factory class.
We do have a Factory class named as Factory Class, Factory class is responsible to create an object and its initiation .Factory class has one method named as CreateMobileObject which creates an object on behalf of the parameter being passed by user (client) and returns mobile type.
Code snippet for Factory class:

  1: public static class FactoryClass
  2: {
  3:     public static IMobile CreateMobileObject(MobileType mobileType)
  4:     {
  5:         IMobile objIMobile = null;
  6:         switch (mobileType)
  7:         {
  8:             case MobileType.Samsung:
  9:                 objIMobile = new Samsung();
 10:                 return objIMobile;
 11: 
 12:             case MobileType.Apple:
 13:                 objIMobile = new Apple();
 14:                 return objIMobile;
 15: 
 16:             case MobileType.Nokia:
 17:                 objIMobile = new Nokia();
 18:                 return objIMobile;
 19: 
 20:             default:
 21:                 return null;
 22: 
 23:         }
 24:     }
 25: }
There are few classes which I’ve built for mobile classes which implements IMobile interface.

  1:  public class Samsung : IMobile
  2:     {
  3:         public string ModelName()
  4:         {
  5:             return "Samsung Galaxy Grand";
  6:         }
  7: 
  8:         public string OperatingSystem()
  9: 
 10:         { return "Samsung Uses Android OS For Galaxy Mobile series "; }
 11: 
 12:     }
 13: 
 14:     public class Apple : IMobile
 15:     {
 16:         public string ModelName()
 17:         {
 18:             return "Apple IPhone 5";
 19:         }
 20: 
 21:         public string OperatingSystem()
 22: 
 23:         { return "Apple Uses ios OS for Apple Mobiles "; }
 24: 
 25:     }
 26: 
 27:     public class Nokia : IMobile
 28:     {
 29:         public string ModelName()
 30:         {
 31:             return "Nokia Lumia 960";
 32:         }
 33: 
 34:         public string OperatingSystem()
 35: 
 36:         { return "Nokia Uses Symbion OS for Lumia Mobile series "; }
 37: 
 38:     }
Now moving further and pass a parameter to the static method CreateMobileObject() accepts a parameter of desired type.

Code snippet for the Main is as follows:


clip_image006

Press F5 and you will get the result like the below black window:
clip_image008
The above image gives you the details of two mobiles which we passed into factory class method.

Advantages

· Easy to implement
· Client application code doesn’t have to change drastically
· Moreover, the tight coupling between client and mobile classes is overcome and turned into coupling between factory and mobile classes. Hence client need not know the instantiation logic of products.
Disadvantages

· If we add any new product (mobile), we need a new case statement in CreateMobileObject method of Factory class. This violates open/closed design principle.
· We can avoid modifying the Factory class by using sub classing. But sub classing means replacing all the factory class references everywhere through the code.
· We have tight coupling between Factory class and products.
·
Sample App is attached as an reference.
Thanks,
Keep Coding and Be Happy Smile









































Saturday, May 3, 2014

Demystify WebApi Content negotiation

Demystify WebApi Content negotiation

In this article we will look into the heart of ASP.Net WebApi content negotiation or conneg. We will try to understand the real advantages and why it has been introduced. I thought it would be interesting to try to explain content negotiation in detail

What is content negotiation or conneg?

Content negotiation has been defined by W3C. It is the process of selecting the best representation for a given response when there are multiple representations available.

Content negotiation (conneg) in ASP.NET Web API is an intrinsic server-driven mechanism used to determine, based on the client’s request, which media type formatter (out of box there are 4 media type formatters ) is going to be used to return an API response.In general client send the Accept parameter in Request Header to determine the response , Apart from this Web API smart enough to decides which repsonse format is best. In .NET, it really comes down to deciding on how to send down your CLR object to the client, over HTTP or From the ASP.NET Web API perspective, serialization is the process of translating a .NET Common Language Runtime (CLR) type into a format that can be transmitted over HTTP. The default format I are either JSON or XML.

Serialization

If a Web API controller returns a resource as CLR type, the pipeline serializes the return value and writes it into the HTTP response body.

For example, consider the following controller action: Reference MSDN

  1: public Product GetProduct(int id)
  2: {  
  3:    var item = _products.FirstOrDefault(p => p.ID == id); 
  4:    if (item == null)   
  5:    {       
  6:       throw new HttpResponseException(HttpStatusCode.NotFound);
  7:    }  
  8:        return item;
  9:  }
A client might send this HTTP request:
  1: GET http://localhost.:21069/api/products/1 HTTP/1.1
  2: Host: localhost.:21069
  3: Accept: application/json, text/javascript, */*; q=0.01

In response, the server might send:

  1: HTTP/1.1 200 OK
  2: Content-Type: application/json; charset=utf-8Content-Length: 57
  3: Connection: Close 
  4: {"Id":1,"Name":"Gizmo","Category":"Widgets","Price":1.99}

In this example, the client requested either JSON, Javascript, or “anything” (*/*). The server responsed with a JSON representation of the Product object. Notice that the Content-Type header in the response is set to "application/json"

 

Before proceeding further, we need to explain two more important terms, around which the content negotiation is built.
Media type is defined again by W3C as being used “in the Content-Type and Accept header fields in order to provide open and extensible data typing and type negotiation.” Examples of media type can be application/json, application/xml, application/rss+xml, application/html, text/plain
Media type formatter is a class which writes/reads a CLR object to/from the body of the HTTP response/request (depending on the information flow direction).

Conneg mechanism itself is part of GlobalConfiguration.Services collection and can be retrieved using the GlobalConfiguration.Services.GetContentNegotiation () method.

Conneg formatters are part of the GlobalConfiguration.Formatters collection, and as such can be easily accessed from anywhere within your Web API application context.

Out of Box Web API ships with 4 formatters, in the following order (order is important, since when no good matches can be found, Web API uses formatters in the order they appear):

To know more in how Web API uses MediaTypeFormatter to respond to request.

WebApi: MediaTypeFormatters in WebApi

Manage WebApi Response using Media Types of MediaTypeFormatters

Though this is the order of handling a request from MediaType Formatter.

– System.Net.Http.Formatting.JsonMediaTypeFormatter, based on JSON.NET
– System.Net.Http.Formatting.XmlMediaTypeFormatter, based on DataContractSerializer
– System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter, for handling HTML form URL-encoded data
– System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter, for handling model-bound HTML form URL-encoded data

How content negotiation is performed?

In Web API, there are 4 criteria before deciding on the media formatter to use, in descending

order of precedence:

1. Media Type Mapping
A MediaTypeMapping allows you to map the request or response messages that have certain characteristics to a media-type. Web API ships with 4 different media type mappings:
– QueryStringMapping,
– UriPathExtensionMapping,
– RequestHeaderMapping
– MediaRangeMapping.

2. Accept headers in the request
Accept headers issued by the client are the second most important criteria. Let’s say your client makes a request and includes the following headers entry.This request is handled by Conneg.

clip_image001

3. Content type of the body
The next in line is the content type of the request. If the request incoming to the Web API is of specific content type (contains specific media type like application/json,application/xml), and either MediaTypeMappings decide otherwise or Accept headers are not present, conneg algorithm resorts to inspecting the Content Type of the request.

Note: If both Accept and Content-Type are present, obviously Accept takes precedence.

4. Checking if the formatter can serialize the response content’s model

If, for a given request, any of all above 3 criteria doesn’t match, conneg mechanism simply starts going through all the available formatters in the GlobalConfiguration.Formatters collection in the order they are stored there and checks whether the return type can be written by each formatter.

The first formatter that can serialize the type is chosen or on first match, the search process is terminated and the matched formatter is used by Web API to return the response to the client or

Hope after reading this you may be able to understand the content negotiation.

Friday, May 2, 2014

Meaning of Scaffolding in MVC

Scaffolding in MVC

I was slightly confused with the meaning of Scaffolding in MVC. Fortunately, I confronted some very nice lines that I am sharing here so that it helps those who are not familiar with Scaffolding.

The term "Scaffolding" is used by many software technologies to mean "quickly generating a basic outline of your software that you can then edit and customize". Here in MVC 3, the scaffolding feature provides us auto-generated Views, Controllers, Database, Table script and so on. All those layers are generated based on the provided model. The fields which are required to be shown / hide in the view can be controlled by the [ScaffoldColumn] attribute. It only gives us the basic layout. With that basic layout, we can customize our apps. Instead of starting our application development from scratch, it gives us some deliverables with which we can design our application.

 

Thanks

Cheers .Net Smile