Pages

Tuesday 24 April 2012

DOM Events: Mouse Events, Keyboard Events, Form Events, Frame Events and Touch Events

Mouse Events

1. Click Event (onclick): The event occurs when the user clicks on an element.
2. Double Click Event ( ondblclick): The event occurs when the user double-clicks on an element.
3. Mouse Down (onmousedown): The event occurs when a user presses a mouse button over an element.
4. Mouse Move (onmousemove): The event occurs when a user moves the mouse pointer over an element
5. Mouse Over (onmouseover): The event occurs when a user mouse over an element.
6. Mouse Out (onmouseout): The event occurs when a user moves the mouse pointer out of an element.
7. Mouse Up (onmouseup): The event occurs when a user releases a mouse button over an element.

(Microsoft-specific events for IE)

8. Context Menu (oncontextmenu): Fires when the context menu is shown.
9. Drag (ondrag): Fires when during a mouse drag (on the moving Element).
10. Drag Start (ondragstart): Fires when a mouse drag begins (on the moving Element).
11. Drag Enter (ondragenter): Fires when something is dragged onto an area (on the target Element).
12. Dragover (ondragover): Fires when a drag is held over an area (on the target Element).
13. Drag Leave (ondragleave): Fires when something is dragged out of an area (on the target Element).
14. Drag End (ondragend): Fires when a mouse drag ends (on the moving Element).
15. Drop (ondrop): Fires when a mouse button is released over a valid target during a drag (on the target Element).
16. Select Start(onselectstart): Fires when the user starts to select text.

Keyboard Events

1. Key Down (onkeydown): The event occurs when the user is pressing a key or holding down a key.
2. Key Press (onkeypress): The event occurs when the user is pressing a key or holding down a key.
3. Key Up (onkeyup): The event occurs when a keyboard key is released.

(Microsoft-specific events for IE)

4. Help (onhelp): Fires when the user initiates help.

HTML Frame / Object Events

1. Abort (onabort): The event occurs when an image is stopped from loading before completely loaded.
2. Error (onerror): The event occurs when an image does not load properly (for <object>, <body> and <frameset>). 
3. Load (onload): The event occurs when a document, frameset, or <object> has been loaded.
4. Unload (onunload): The event occurs when a document is removed from a window or frame (for <body> and <frameset>).
5. Resize (onresize): The event occurs when a document view is resized.
6. Scroll (onscroll): The event occurs when a document view is scrolled.

(Microsoft-specific events for IE)

7. Before Unload (onbeforeunload): Fires before a document is unloaded.
8. Stop (onstop): Fires when the user stops loading the object. (unlike abort, stop event can be attached to document) 

Form Events

1. Blur (onblur): The event occurs when a form element loses focus.
2. Change (onchange): The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>).
3. Focus (onfocus): The event occurs when an element gets focus (for <label>, <input>, <select>, textarea>, and <button>).
4. Reset (onreset): The event occurs when a form is reset.
5. Select (onselect): The event occurs when a user selects some  text (for <input> and <textarea>) .
6. Submit (onsubmit): The event occurs when a form is submitted.

(Microsoft-specific events for IE)

7. Before Edit Focus (onbeforeeditfocus): Fires before an element gains focus for editing.

Miscellaneous Microsoft-specific events for IE

1. Before Print (onbeforeprint): Fires before a document is printed.
2. After Print (onafterprint): Fires immediately after the document prints.
3. Property Change (onpropertychange): Fires when the property of an object is changed.
4. Filter Change (onfilterchange): Fires when a filter changes properties or finishes a transition.
5. Readystate Change (onreadystatechange): Fires when the readyState property of an element changes.
6. Lose Capture (onlosecapture): Fires when the releaseCapture method is invoked.

Touch Events

Web browsers running on modern, touch-enabled devices have events, such as "touchstart", "touchend", "touchenter", "touchleave", "touchmove", and "touchcancel". Apple's iOS and Google's Android are two examples of mobile operating systems with support for these events in their web browsers.

When you put a finger down on the screen of the touch enabled devices, it kicks off the lifecycle of touch events and the following events get triggered.

touchstart: When a finger is placed on the touch surface/screen.
touchend: When a finger is removed from the touch surface/screen.
touchmove: When a finger already placed on the screen is moved across the screen.
touchenter: When a touch point moves onto the interactive area defined by a DOM element.
touchleave: When a touch point moves off the interactive area defined by a DOM element.
touchcancel: A user agent must dispatch this event type to indicate when a TouchPoint has been disrupted in an implementation-specific manner, such as by moving outside the bounds of the UA window. A user agent may also dispatch this event type when the user places more touch points (The coordinate point at which a pointer (e.g. finger or stylus) intersects the target surface of an interface) on the touch surface than the device or implementation is configured to store, in which case the earliest TouchPoint object in the TouchList should be removed.

What is DOM (Document Object Model): Tree and Node Structure of HTML Page

The Document Object Model (DOM) defines a standard way for accessing and manipulating HTML documents. The DOM presents an HTML document as a TREE-STRUCTURE. The DOM is a W3C (World Wide Web Consortium) standard. The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

The Document Object Model (DOM) is the model that describes how all elements in an HTML page, like input fields, images, paragraphs etc., are related to the topmost structure: the document itself.

DOM: The Tree and Node Structure

The HTML DOM views an HTML document as a tree-structure. The tree structure is called a node-tree. In the DOM, everything in an HTML document is a node. All nodes can be accessed through the tree. Their contents can be modified or deleted, and new elements can be created.

Note: The Root Node of DOM Tree is DOCUMENT.

document.documentElement - returns the root node of the document
document.body - gives direct access to the <body> tag

The nodes in the node tree have a hierarchical relationship to each other. On the basis of hierarchy, Nodes can be divided into three categories:

1. Parent Nodes
2. Child Nodes
3. Sibling Nodes:
  Child Nodes on the same level are called siblings (brothers or sisters).

Example:

<p>This is a paragraph</p>

Here "p" is parent node and 'This is a paragraph' is a child node.

Note:

1. In a node tree, the top node is called the root
2. Every node, except the root, has exactly one parent node
3. A node can have any number of children
4. A leaf is a node with no children
5. Siblings are nodes with the same parent

Nodes can also be classified as:

1. Element Nodes: Every HTML element is an element node
2. Text Nodes: The text in the HTML elements are text nodes. In the HTML DOM the value of the text node can be accessed by the innerHTML property.
3. Attribute Nodes: Every HTML attribute is an attribute node
4. Comment Nodes: Comments are also treated as nodes in DOM.
5. Document Node: It is the parent node of DOM.. The entire document is a document node

Example:

<p align="right">This is a paragraph</p>

Here "p" is element node, 'This is a paragraph" is a text node and "align" is the attribute node.

Node Properties

In the HTML DOM, each node is an object.Objects have methods and properties that can be accessed and manipulated by JavaScript. Three important node properties are:

1. nodeName
2. nodeValue
3. nodeType

The nodeName Property

The nodeName property specifies the name of a node.

1. nodeName is read-only
2. nodeName of an element node is the same as the tag name
3. nodeName of an attribute node is the attribute name
4. nodeName of a text node is always #text
5. nodeName of the document node is always #document

Note: nodeName always contains the uppercase tag name of an HTML element.

The nodeValue Property

1. The nodeValue property specifies the value of a node.
2. nodeValue for element nodes is undefined
3. nodeValue for text nodes is the text itself
4. nodeValue for attribute nodes is the attribute value

The nodeType Property

The nodeType property returns the type of node. nodeType is read only.
The most important node types are: Element Node, Text Node, Attribute Node, Comment Node and Document Node

HTML DOM Methods:

x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x

Note: In the list above, x is a node object (HTML element or node, say document).

HTML DOM Properties

x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x

Note: In the list above, x is a node object (HTML element or node, say <p>).

DocType: Strict, Transitional and Frameset

The DOCTYPE element is an identifier found at the very beginning of an HTML document, even before the element.
 
DocType declares to the browser what version of (X)HTML (eg. 3.4 or 4.01, 5.0 etc.) is used in the document. DocType is not an HTML Tag.

Syntax of DocType and Explanation:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

!DOCTYPE: The identifier. It indicates to the user-agent that the enclosed information will define the type of document of the page.

HTML: The Top Element. This tells the browser what element to expect as the top-level element. For HTML and XHTML documents this element would be <html>

PUBLIC: The Availability. The most common DOCTYPES you will use will be publicly available. But you can also specify a local DTD with the "SYSTEM" key word.

"-//W3C//DTD HTML 4.01 Transitional//EN": The Formal Public Identifier (FPI).

The FPI is made up of these parts:

Registration. If there is a plus-sign (+) here, that means that the organization is registered with the ISO. A minus-sign (-) indicates that it is not registered.

W3C: The Organization. This is the group that owns and maintains the DOCTYPE being used.

DTD: The Type. This defines the type of DOCTYPE used. A Document Type Definition (DTD) defines the legal building blocks of an XML/HTML document. It defines the document structure with a list of legal elements and attributes.

HTML 4.01 Transitional: The Human-Readable Label. This is the label that tells you what DTD is being used. It is written so that humans, rather than computers, can understand it.
EN: The Language. This is the language that the DTD is written in. It is not the language of the content of the page.

The rest of the DOCTYPE identifier is optional: "http://www.w3.org/TR/html4/loose.dtd": It is used to indicate where the DTD for this DOCTYPE can be found
 
DocType is also used to describe the particular flavor of HTML you're using.

For example: There are three variants on HTML 4.01:

1. HTML 4.01 Strict, which describes the structural portions of HTML 4.01 and does not provide any presentational markup or frame-related markup. HTML 4.0 Strict says you to use an Cascading Style Sheet for presentational markup (<b>, <font> etc.) and not to include these elements in HTML page. This DocType claims that the document is a strict document; that is, it is authored according to a strict adherence to the W3C specification, and uses no presentational markup (<b>, <font> etc.). Upon seeing this, IE5/Mac will kick its rendering engine into STANDARD MODE, so that your document will be displayed according to the W3C standards.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

2. HTML 4.01 Transitional, which includes the presentational markup such as and , but does not include frame-related markup. Transitional DTD allows some older PUBLIC and attributes that have been deprecated. This declaration calls for transitional (or loose) adherence to the standards. In this case, IE5/Mac will display the document according to bugwards compatibility rules (Quirk Mode). This will bring the rendering more in line with Internet Explorer for Mac's historical behavior. Upon seeing this, IE5/Mac will kick its rendering engine into QUIRK MODE.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

You'll notice that neither example included the URL of a DTD. This was on purpose. If you include the URL of a DTD on any DOCTYPE, even the loose and frameset kinds, then IE5/Mac will go into STRICT MODE. This may lead to unexpected results, as the rendering engine will no longer attempt to emulate historical browser flaws.

Note: There are two types of webpage rendering mode of a brower: Standard Mode and Quirk Mode.

3. HTML 4.01 Frameset, which is the same as HTML 4.01 Transitional except that it adds a description of frame-related markup. If frames are used, the Frameset DTD must be used.

HTML5 DTD-less DOCTYPE

HTML5 uses a DOCTYPE declaration which is very short, due to its lack of references to a Document Type Definition in the form of a URL and/or FPI. All it contains is the tag name of the root element of the document, HTML.

 <!DOCTYPE HTML>

What if DocType is absent in HTML document?

1. An HTML document which lacks a DOCTYPE, will be rendered in bugwards compatibility mode (Quirk Mode), since it is assumed to be an older document which was written before DOCTYPE became widely used.

2.You will not be able to use a HTML (HyperText Markup Language) Validator to check the page coding. HTML validator requires the DOCTYPE declaration.

3.The stylesheet may not be implemented as planned.

Monday 23 April 2012

How the ASP.NET authentication process works?

ASP.NET does not run by itself, it runs inside the process of IIS. Therefore, there are two authentication layers, which exist in ASP.NET system. First authentication happens at the IIS level and then at the ASP.NET level depending on the WEB.CONFIG file.

Below is how the whole process of authentication in ASP.NET works?

1. IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not it denies the request.

2. Next IIS performs its own user authentication if it is configured to do so. By default IIS allows anonymous access, so requests are automatically authenticated, but you can change this default on a per – application basis with in IIS.

3. If the request is passed to ASP.NET with an authenticated user, ASP.NET checks to see whether impersonation is enabled. If impersonation is enabled, ASP.NET acts as though it were the authenticated user. If not ASP.NET acts with its own configured account.

*Impersonation:  Impersonation is when ASP.NET executes code in the context of an authenticated and authorized client. By default, ASP.NET does not use impersonation and instead executes all code using the same user account as the ASP.NET process, which is typically the ASPNET account.

4. Finally, the identity from step 3 is used to request resources from the operating system. If ASP.NET authentication can obtain all the necessary resources, it grants the users request otherwise it is denied. Resources can include much more than just the ASP.NET page itself you can also use .NET’s code access security features to extend this authorization step to disk files, Registry keys and other resources.

Response.Redirect vs Server.Transfer: What to use when? An 11 point comparision

1. Response.Redirect simply sends a message to the browser, directing it to move to another page.

Example:

Response.Redirect("default.aspx");
or
Response.Redirect("
http://www.dzone.com");

On the other hand, Server.Transfer does not initiate another request to the server, but the original request is simply rewritten and transfered to some other page on the same server.

Example: Sever.Transfer("default.aspx");

2. Server.Transfer changes the "focus" on the Webserver and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster. On the other hand, Response.Redirect will instruct browser to call a particular webpage.This will increase one request and one response between the client and server. This extra round-trip is often inefficient and unnecessary.

3. Server.Transfer maintains the original URL in the browser but Response.Redirect changes the URL.

4. The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("default.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to. By default, this variable is always true.

For example, if your default.aspx has a TextBox control called "TextBox1" and you transferred to default2.aspx with the preserveForm parameter set to True, you would be able to retrieve value of the "TextBox1" of default.aspx by using "PreviousPage.FindControl" method.
But in case of Respons.Redirect, by the time default2.aspx is requested, default.aspx is flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc.

5. By Response.Redirect, we can navigate to another page in same site as well as different site, but by Server.Transfer we can only navigate the page that exists in same website.

6. Server .Transfer will also cause confusion when user refreshes the page. If user is on Page1 and by using Server.Transfer, user sees the Page2. The url on browser is still of Page1. So, if user refreshes the page, Page1 will be refreshed instead of Page2. This problem will never appear in case of Response.Redirect.

7. Server.Transfer may cause confusion while debugging as the URL does not change unlike Response.Redirect.

8. Response.Redirect is used like GET method in which we can see all information or address where we will be go. Server.Transfer is used like POST method in which one cannot see full address.

9. Resonse.redirect can be used both for aspx and html pages. But server.transfer is only used for aspx pages it will not work for html pages.

10. In case of Server.Transfer the browser's history is not updated but in Response.Redirect the browser's history is updated.

11. Bookmarking is ambiguous in case of Server.Transfer while in Response.Redirect, user can clearly bookmark a page.

Summary: What should be used where?

Response.Redirect should be used when:

1. We want to redirect the request to some plain HTML pages on our server or to some other web server.
2. We don't care about causing additional roundtrips to the server on each request.
3. We do not need to preserve Query String and Form Variables from the original request.
4. We want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to
bookmark it if its necessary)

Server.Transfer should be used when:

1. We want to transfer current page request to another .aspx page on the same server.
2. We want to preserve server resources and avoid the unnecessary roundtrips to the server.
3. We want to preserve Query String and Form Variables.
4. We don't need to show the real URL where we redirected the request in the users Web Browser
 

Sunday 22 April 2012

GET vs POST: Which one is better? A 10 point comparision

1. Data Size Restriction in GET: There is a character restriction of 255 in the URL. This is mostly the old browsers restriction and new ones can handle more than that. But we can't be sure that all our visitors are using new browsers. So when we show a text area or a text box asking users to enter some data, then there will be a problem if more data is entered. This restriction is not there in POST method. We can transfer unlimited data using POST. In PHP by default 8MB of data can be transferred. (can be changed by setting the post_max_size in the php.ini file)

2. Data Type Restriction in GET: As the data transfers through address bar ( URL ) there are some restrictions in using space, some characters like ampersand ( & ) etc in the GET method of posting data. We have to take special care for encoding (while sending) and decoding (while receiving) data if such special characters are present.

3. Security: In GET method data gets transferred to the processing page in name value pairs as a query string in URL, so it is exposed and can be easily traced by visiting history pages of the browser. Data is always submitted in the form of text. So any login details with password should never be posted by using GET method. On the other hand, POST is much more secure. In case of POST, all the name value pairs are submitted in the Message Body of the request.

4. Speed: GET is faster than POST.

5. Bookmarking: There are some special cases where advantage of using GET method is, one can store the name value pairs as bookmark and directly use them by bypassing the form. But you cannot bookmark using POST method.

6. If POST method is used and if the page is refreshed it would prompt before the request is resubmitted but it would not prompt if GET method is used.

7. Uploading files through input type file is possible in POST but not with GET method.

8. There are chances for data lost after server encoding in GET method but no data loss occurs in case of POST method.

9. GET uses STACK method for passing form variables while POST method uses HEAP method for passing form variables.

10. GET can store up to 18 form variables but there is no limit in case of POST method.

HTTP vs HTTPS: Similarities and Differences

What is HTTPS?

HTTPS (Hypertext Transfer Protocol over Secure Socket Layer, or HTTP over SSL) is a web protocol developed by Netscape.

One can say: HTTPS = HTTP + SSL

HTTPS uses Secure Socket Layer (SSL) as a sublayer under its regular HTTP application layering.

Need of HTTPS:

Hypertext Transfer Protocol (HTTP) is a protocol for transmitting and receiving information across the Internet. HTTP serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. You normally use HTTP when you are browsing the web, its not secure, so someone can eavesdrop on the conversation between your computer and the web server. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape corporation to allow authorization and secured transactions.

Similarity between HTTP and HTTPS:

In many ways, https is identical to http, because it follows the same basic protocols. The http or https client, such as a Web browser, establishes a connection to a server on a standard port. When a server receives a request, it returns a status and a message, which may contain the requested information or indicate an error if part of the process malfunctioned. Both systems use the same Uniform Resource Identifier (URI) scheme, so that resources can be universally identified. Use of https in a URI scheme rather than http indicates that an encrypted connection is desired.

Difference between HTTP and HTTPS:

1. URL begins with “http://" in case of HTTP while the URL begins with “https://” in case of HTTPS.
2. HTTP is unsecured while HTTPS is secured.
3. HTTP uses port 80 for communication while HTTPS uses port 443 for communication.
4. HTTP operates at Application Layer while HTTPS operates at Transport Layer.
5. No encryption is there in HTTP while HTTPS uses encryption.
6. No certificates required in HTTP while certificates required in HTTPS.

How HTTPS works?

For HTTPS connection, public key and signed certificates are required for the server.
When using an https connection, the server responds to the initial connection by offering a list of encryption methods it supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both parties exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. In order to host https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Most certificates are verified by a third party so that clients are assured that the key is secure.
In other words, we can say, HTTPS works similar to HTTP but SSL adds some spice in it.

HTTP includes the following actions:

1. The browser opens a TCP connection.
2. The browser sends a HTTP request to the server
3. The server sends a HTTP response to the browser.
4. The TCP connection is closed.

SSL will include the following actions:

1. Authenticate the server to the client.
2. Allow the client and server to select the cryptographic algorithms, or ciphers, that they both support.
3. Optionally authenticate the client to the server.
4. Use public-key encryption techniques to generate shared secrets.
5. Establish an encrypted SSL connection.
6. Once the SSL connection is established the usual transfer of HTTP requests will continue.

Where should https be used?

HTTPS should be used in Banking Websites, Payment Gateway, Shopping Websites, Login Pages, Emails (Gmail offers HTTPS by default in Chrome browser) and Corporate Sector Websites. For example:


Beware of using Credit Card Numbers on Internet:  If a website ever asks you to enter your credit card information, you should automatically look to see if the web address begins with https://. If it doesn't, there's no way you're going to enter sensitive information like a credit card number!

Browser integration

Most browsers display a warning if they receive an invalid certificate. Older browsers, when connecting to a site with an invalid certificate, would present the user with a dialog box asking if they wanted to continue. Newer browsers display a warning across the entire window. Newer browsers also prominently display the site's security information in the address bar. Extended validation certificates turn the address bar green in newer browsers. Most browsers also display a warning to the user when visiting a site that contains a mixture of encrypted and unencrypted content.

Friday 20 April 2012

How IIS processes ASP.NET request?

Before understanding the full flow, we have to go through following concepts:

IIS: IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it’s own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.

Worker Porcess (w3wp.exe): Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. In short, Worker process is the heart of ASP.NET Web Application which runs on IIS.

Application Pool: Application pool is the container of worker process. Application pools is used to separate the sets of IIS worker processes that share the same configuration. This makes sure that a particular web application doesn’t not impact other web application.

Note: One Application Pool can have one or many Worker Processes. An application pool with more than one worker process is called 'Web Garden'.

HTTP.SYS Process: HTTP.SYS resides in Kernel Layer of IIS. HTTP.SYS is responsible for pass the request to particular Application pool. It contains the ID of each Application Pool. (Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS).

WAS (Web Admin Services): WAS resides in User Layer of IIS. It takes the request from HTTP.SYS and pass it to the respective application pool.

ISAPI extensions: ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.

Note: Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.

Flow of ASP.NET Request:

1. Client Request hits the web server. Internally this request comes to Kernel Layer of IIS means at HTTP.SYS.

2. HTTP.SYS indentifies the name and ID of Application Pool for that ASP.NET Request.

3. Now Request comes to user level of IIS. WAS (Web Admin Service) puts the request from HTTP.SYS to Application Pool.

4. When Application pool receive the request, it simply pass the request to worker process (w3wp.exe).

5. The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension (aspnet_isapi.dll).

6. ISAPI creates an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder.HTTPRuntime is an entry point of the application.

Note: After these steps, After that the ASP.NET Page LifeCycle events starts.

Conclusion:

HTTP.SYS  (Kernel Layer) --> WAS (Web Admin Services) (User Layer) --> Application Pool --> Worker Process (w3wp.exe) --> ISAPI Process (aspnet_isapi.dll) -->  HTTPRuntime Process

AutoEventWireup in ASP.NET: Why my ASP.NET events fire twice?

Here is a brief description of AutoEventWireup attribute in ASP.NET.

1. AutoEventWireup is an attribute in Page directive. 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

We can specify the default value of the AutoEventWireup attribute in the following locations:

1. The Machine.config file.
2. The Web.config file.
3. Individual Web Forms (.aspx files).
4. Web User Controls (.ascx files)

If you make these changes in the Machine.config file, the changes affect all ASP.NET Web Forms on the computer. If you make these changes in the Web.config file, the changes affect only the application that the file belongs to. However, to make changes in the individual Web Form Only, we have to add the AutoEventWireup attribute to the @ Page directive, as shown above.

2. AutoEventWireup is a Boolean attribute that indicates whether the ASP.NET pages events are auto-wired.

3. AutoEventWireup will have a value true or false. By default it is true in C# and false in VB.NET.
VB.NET has a mechanism for defining an event handler and subscribing to an event with the 'Handles' keyword.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

There is no equivalent to the Handles keyword in C#. Thats why AutoEventWireup is by default true in C#.

protected void Page_Load(object sender, EventArgs e)
{
}

AutoEvenWireup = "TRUE"

The ASP.NET page framework supports an automatic way to associate page events and methods. If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. In that case, no explicit Handles clause or delegate is needed.

AutoEventWireup = "FALSE"

If you do set AutoEventWireup to false, Visual Studio will not be able to generate code to bind the events. In this case, you must define explicit Handles clause or delegate.

public partial class _Default : Page
{
   public _Default()
   {
      Load += new EventHandler(Page_Load);
      PreInit += new EventHandler(Page_PreInit);        
   }
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
   protected void Page_PreInit(object sender, EventArgs e)
   {
     
   }
}

Why my ASP.NET events fire twice?

A very common question asked. The simple answer to this question is:

If you have AutoEventWiureUp="TRUE" as well as you also have defined delegates for the event handling in your code, .NET Framework will automatically call methods based on their names and also the methods you defined explicitly.

Disadvantage of AutoEventWireup = "TRUE"

1. The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers.

2. If you do set AutoEventWireup to true and also defined event handlers, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.

3. Performance Issue: Another disadvantage is that performance is adversely affected, because ASP.NET searches for methods at run-time. For a Web site with high traffic volumes, the impact on performance could be significant.

Thursday 19 April 2012

Web Farms in ASP.NET: Advantages and Issues

Web Farm: When we host a web application over multiple web server to distribute the load among them is called Web Farm. Web Farms are Load Balanced.

Need of Web Farm: After developing our asp.net web application, we host it on web server.  Now one standalone server is sufficient to process ASP.NET Request and response for small web sites but when the site comes for big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This arises the need of web farms. You can increase the number of servers in web farms as your traffic increases.

Role of Load Balancer in Web Farms: Load Balancer IP is exposed to external worlds to access. So whenever some request will come to server from clients, it will first hit the Load Balancer, then based on the traffic on each server Load Balancer distribute the request to corresponding web server. These web servers may share same database server or may be they can use replicated server in the back end.

Advantages of Web Farm

1. It provides high availability. If any of the servers in the farm goes down, Load balancer can redirects the requests to other servers.
2. Provides high performance response for client requests.
3. Provides Better scalability of the web application and reduce the failure of application.
4. Session and other resource can be stored in a centralized location to access by the all server.

Issues with Web Farms:

There are many issues with web farms:

1.State management (Cookies, ViewState, Sessions etc)
2.Caching and Cache invalidation
3.Database loading (managing round-trips, partitioning, disk subsystem, etc)
4.Application pool management (WSRM, pool resets, partitioning)
5.Deployment
6.Monitoring

How to manage Session in Web Farm Mode?

Let’s take an example:

When a user selects an item from a DropDownList and then clicks a submit button, the Click event on the button redirects them to the value of the selected item. This works fine if you are on Webserver1 and the button click PostBacks to Webserver1. If you are on Webserver1 and the load balance submits back to Webserver2, the page reloads and the Button click event never fires.

Solution: While using session, requests are distributed among different servers. By default session mode is set to In Proc where session data stored inside worker process memory. But, In Web farm mode we can share the session among the entire server using a single session store location my making it Out proc (State Server or SQL Server Mode). So, if some of the server goes down and request transferred to the other server by the Load balancer session data should be available for that request.

How to solve caching issues? Centralized Cache location

One Cache-application is to be created, which will take care of the caching and returning the cached items. And that is to be placed in centralized location. All applications should send the data to be cached, to that cache-application. The Cache-application will store the data. When any application requests the cached data, it will be retrieved from the Cache-application. (The centralized Cache-application can be called with credentials.)

SQL server caching

SQL Server caching is easy to implement by using ADO.NET and the .NET Framework, and it provides a common development model to use with existing data access components. It provides a robust security model that can easily be configured to work across a Web farm using SQL Server replication.

If the application requires cached data to persist across process recycles, reboots, and power failures, in-memory cache is not an option. In such cases, Caching mechanism based on a persistent data store, such as SQL Server or the NTFS file system. It also makes sense to use SQL Server to cache smaller data items to gain persistency.

Because the cache service needs to access SQL Server over a network and the data is retrieved using database queries, the data access is relatively slow. We need to carefully compare the cost of recreating the data versus retrieving it from the database.

Monitoring: To detect problems that affect a single server or the whole site, you must monitor both the external URL for the site and the URLs for each of the Web servers.

Synchronize Configuration and Content:

You need to ensure that the config files are present in the right path on all the servers, and that their contents are continuously in sync.

Cautions while dropping a tablespace

DROP TABLESPACE drops the tablespace from database. But, there are few things which you should take care while firing this statement.

1. DROP TABLESPACE myTablespace;

- drops the tablespace

Cautions:

A) You cannot drop the SYSTEM tablespace.

B) You can drop the SYSAUX tablespace only if you have the SYSDBA system privilege and you have started the database in MIGRATE mode.

C) You cannot use this statement to drop a tablespace group. However, if tablespace is the only tablespace in a tablespace group, then Oracle Database removes the tablespace group from the data dictionary as well.

D) When you drop a tablespace, Oracle Database does not place it in the recycle bin means your data is not recoverable. Therefore, make sure that all data contained in a tablespace to be dropped will not be required in the future.

E) Also, immediately before and after dropping a tablespace from a database, back up the database completely. This is strongly recommended so that you can recover the database if you mistakenly drop a tablespace, or if the database experiences a problem in the future after the tablespace has been dropped.

2. DROP TABLESPACE myTablespace
    INCLUDING CONTENTS
    CASCADE CONSTRAINTS;

-drops the myTablespace tablespace and drops all referential integrity constraints that refer to primary and unique keys inside myTablespace

Cautions:

1. For partitioned tables, DROP TABLESPACE will fail even if you specify INCLUDING CONTENTS, if the tablespace contains some, but not all. If all the partitions of a partitioned table reside in tablespace, then DROP TABLESPACE ... INCLUDING CONTENTS will drop tablespace.

3. DROP TABLESPACE myTablespace
   INCLUDING CONTENTS AND DATAFILES;

-drops the myTablespace tablespace and deletes all associated operating system datafiles.

Suggestion: You can drop a tablespace regardless of whether it is online or offline. But it is suggested that you take the tablespace offline before dropping it to ensure that no SQL statements in currently running transactions access any of the objects in the tablespace.

Wednesday 18 April 2012

12 Point Comparision between FTP and HTTP Protocols (File Uploading / Downloading)

Many sites, such as Facebook or a blog, will allow a user to upload or download files to the site for a myriad of reasons, such as pictures for a website or files for a forum or blog software. In either case, there are two ways to upload a file to a server or website: using HTTP or using FTP.

Here are some of the differences:

1. HTTP is used to view websites while FTP is used to access and transfer files. FTP's file transfer purpose is more or less for website maintenance and batch uploads, while HTTP is for client-end work and for end users to upload things such as movies, pictures and other files to the server.

2. HTTP and FTP clients: The common HTTP client is the browser while FTP can be accessed via the command line or a graphical client of its own.

3. HTTP Headers: HTTP Headers contains metadata such as last modified date, character encoding, server name and version and more which is absent in FTP.

4. Age Difference: FTP is about 10 years older than HTTP.

5. Data Formats: FTP can send data both in ASCII and Binary Format but HTTP only uses Binary Format.

6. Pipelining in HTTP: HTTP supports pipelining. It means that a client can ask for the next transfer already before the  previous one has ended, which thus allows multiple documents to get sent without a round-trip delay  between the documents, but this pipelining is missing in FTP.

7. Dynamic Port Numbers in HTTP: One of the biggest hurdles about FTP in real life is its use of two connections. It uses a first primary connection to send control commands on, and when it sends or receives data, it opens a second TCP stream for that purpose. HTTP uses dynamic port numbers and can go in either direction,

8. Persistent Connection in HTTP: For HTTP communication, a client can maintain a single connection to a server and just keep using that for any amount of transfers. FTP must create a new one for each new data transfer. Repeatedly making new connections are bad for performance due to having to do new handshakes/connections all the time.

9. Compression Algorithms in HTTP: HTTP provides a way for the client and server to negotiate and choose among several compression algorithms. The gzip algorithm being the perhaps most compact one but such kind of sophisticated algorithms are not present in FTP.

10. Support for Proxies in HTTP: One of the biggest selling points for HTTP over FTP is its support for proxies, already built-in into the protocol.

11. One area in which FTP stands out somewhat is that it is a protocol that is directly on file level. It means that FTP has for example commands for listing dir contents of the remote server, while HTTP has no such concept.

12. Speed: Possibly the most common question: which is faster for transfers?

What makes FTP faster?

1. No added meta-data in the sent files, just the raw binary
2. Never chunked encoding "overhead"

What makes HTTP faster?

1. Reusing existing persistent connections make better TCP performance
2. Pipelining makes asking for multiple files from the same server faster
3. Automatic compression makes less data get sent
4. No command/response flow minimizes extra round-trips

Conclusion: Ultimately the net outcome of course differ depending on specific details, but I would say that for single-shot static files, you won't be able to measure a difference. For a single shot small file, you might get it faster with FTP (unless the server is at a long round-trip distance). When getting multiple files, HTTP should be the faster one.

Dataset, Dataview, Datatable and common operations on them

DataTable:

• DataTable is a logical representation of data in terms of rows and columns.
• DataSet stores retrieved data from database into DataTables.
• If DataSet fetches data from more than one table, it stores them in different DataTables.

DataRow and DataColumn:

• DataRow and DataColumn are the components of DataTable.
• DataRow represents the row and DataColumn represents the column in DataTable.

DataSet:

• A DataSet is an in-memory representation of a database-like structure.
• Like database, it can have one or more DataTables.
• DataSet is an instance of the datasource like Oracle, SQL Server or Access. It uses disconnected access to database. First a connection is made to database,  then the required data is fetched from database and filled into the DataSet. After that, the connection to database is broken. In this way, using DataSets, saves bandwidth and load on database server.

How to declare and initialize DataSet in Delphi Prsim?

dsMyDataSet : DataSet;
DataSet dsMyDataSet := new DataSet;

How to fill data in DataSet from XML?

dsMyDataSet.ReadXM L(myXMLData);

Above code will fill data into dsMyDataSet from XML file. We can also convert our DataSet into XML file as

dsMyDataSet.WriteXM L(myXMLData);

Here myXMLData is the xml file name.

How to count number of tables contained in a DataSet?

dsMyDataSet.Tables.Count;

How to count number or rows contained in a particular DataTable of a DataSet?

dsMyDataSet.Tables[TableIndex].Rows.Count;  or
dsMyDataSet.Tables[‘TableName’].Rows.Count;

How to access any cell of a DataSet?

dsMyDataSet.Table[TableIndex].Rows [RowIndex].Item[‘ColumnName’].ToString;

How to delete a particular row of a DataSet?

dvMyDataView.Table.Rows [RowIndex].Delete;

How to filter a DataSet?

dsMyDataSet.Table[TableIndex].Select(“ColumnName = ColumnValue”);
For example:
dsMyDataSet.Table[TableIndex].Select(“ID = 123”);
dsMyDataSet.Table[TableIndex]. Select(“ID LIKE 123%”);
Assume ID as column of a DataSet.

How to merge two DataSets?

dsMyDataSet1.Merge(dsMyDataSet2);

DataView:

• A DataView is a logical structure through which we display data contained in the DataTable of DataSet by binding it to DataGrid, DropDownLists, TextBoxes, RatioButtons, CheckBoxes etc.
• A DataView can show the same data or less data than the DataSet. You should declare DataView for a particular DataSet. If  you don’t specify and DataView for your DataSet, a default DataView would get created for it. So if you are binding DataSet with DataGrid, it will not give any compile time or run time error but implicitly, dotnet framework converts that DataSet into dataset.defaultview(0).
• Unlike DataSet, DataView contains only one table.

How to declare and initialize DataView in Delphi Prism?

dvMyDataView : DataView;
DataView dvMyDataView := new DataView;

How to fill data in DataView from DataSet?
 
dvMyDataView := dsMyDataSet.Tables[‘TableName’].DefaultView;    or
dvMyDataView := dsMyDataSet.Tables[TableIndex].DefaultView;

Above code will fill data into dvMyDataView from a particular DataTable of DatSet dsMyDataSet. You can pass either DataTable name or DataTable index to DataSet to retrieve data from a particulat DataTable contained in that DataSet.

How to count number or rows contained in a DataView?

dvMyDataView.Table.Rows.Count;

How to access any cell of a DataView?

dvMyDataView.Table.Rows [RowIndex][‘ColumnName’].ToString;

How to delete a particular row of a DataView?

dvMyDataView.Table.Rows [RowIndex].Delete;

How to filter a DataView?

dvMyDataView.RowFilter := “ColumnName = ColumnValue”;
For example: dvMyDataView.RowFilter := “ID = 123”;
dvMyDataView.RowFilter := “ID LIKE 123%”;
Assume ID as column of a DataView.

Note: We can only filter row of DataView not column.

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.