Friday, 22 March 2013

How the .Net application execution happens?



How the simple web page execution happens?
As all of us know a request comes from Client (Browser) and sends to Server (we call it as Web server) in turn server process the request and sends response back to the client in according to the client request.
But internally in the web server there is quite interesting process that happens. To get aware of that process we should first of all know about the architecture of the IIS
It mainly consists of 3 Parts/Files
  1. Inetinfo.exec
  2. ISAPI Filer (Container for Internet Server Application Interface dlls),
  3. Worker Process (aspnet_wp.exe)
When ever a request comes from the client:
Inetinfo.exe is the ASP.Net request handler that handles the requests from the client .If it's for static resources like HTML files or image files inetinfo.exe process the request and sent to client. If the request is with extension aspx/asp, inetinfo.exe processes the request to API filter. ISAPI filter will have several runtime modules called as ISAPI extensions. To process the request ISAPI filter takes the help of these runtime modules. The runtime module loaded for ASP page is asp.dll. And for ASP.NET page it's ASPNET_ISAPI.dll. From here the request is processed to the "worker process". Worker Process will have several application domains.
Application Domain
The purpose of the application domain is in order to isolate one application from another. When ever we create a new application, application domains are created automatically by the CLRHost. Worker process will create a block of memory related to particular application. Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. Application domains are normally created by runtime hosts. Runtime host is responsible for bootstrapping the common language runtime before an application is run.
Worker process sends the request to HTTPPIPE line.(HTTP Pipeline is nonetheless collection of .net framework classes). HTTP Pipeline compiles the request into a library and makes a call to HTTP runtime and runtime creates an instance of page class
public class File : System.Web.UI.Page{}
ASP.Net web page is a class derived from page class, this page class resides in system.web.dll
After creating instance pf page class HTTP Runtime immediately invokes process request method of page class
Page Req = new Page();
Req.ProcessRequest();
Process Request Method does following things:
  1. Intialize the memory
  2. Load the view state
  3. Page execution and post back events
  4. Rendering HTML content
  5. Releasing the memory
Process Request Method executes set of events for page class .These are called as Page life cycle events.
Page Life Cycle Events
  • Page_Init
    The server controls are loaded and initialized from the Web form's view state. This is the first step in a Web form's life cycle.
  • Page_Load
    The server controls are loaded in the page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.
  • Page_PreRender
    The application is about to render the page object.
  • Page_Unload
    The page is unloaded from memory.
  • Page_Disposed
    The page object is released from memory. This is the last event in the life of a page object.
  • Page_Error
    An unhandled exception occurs.
  • Page_AbortTransaction
    A transaction is aborted.
  • Page_CommitTransaction
    A transaction is accepted.
  • Page_DataBinding
    A server control on the page binds to a data source. 
  • Process Request Method finally renders HTML Page
Dependencies:
When the request comes to ASP.net worker process, it will be forwarded to HTTP Application factory. This "Application Factory" will maintain address of the application domains which are currently executing under worker process. If the required virtual directory application domain is unavailable it will create a new application domain. If the application domain is already existing, the request will be forwarded to corresponding AppDomain.
Application Domain maintains page handler factory class. This will contain all libraries addresses corresponding to webpage. If the requested webpage library is available the instance of the page class is created, if the library is unavailable the request will be forwarded to HTTP pipeline.
Note:
In ASP 2.0 we don't need to install IIS in your system. It comes with built-in ASP server.

ISAPI,WorkerProcess,WebFarm and Webgardening in Asp.Net

What is Worker Process?

"The "Process" which is responsible for processing Asp.net application request and sending back response to the client , is known as "Worker Process". All ASP.NET functionalities runs within the scope of this process."
So finally I can write it...
"Process which is responsible for all asp.net requests and response cycle is known as worker process."
What about Worker process in Web Farm?
A Web farm contains multiple ASP.NET worker processes. 
Each server in the group of servers handles a separate ASP.NET worker process. 
What about Worker process in Web Garden?
A Web garden contains multiple ASP.NET worker processes. 
Each CPU in the SMP server handles a separate ASP.NET worker process. 
Let's See the Worker Process
Running IIS 5.0: Aspnet_wp.ex 
Running IIS 6.0: W3wp.exe
figure1.gif
ISAPI
ISAPI is the first and highest performance entry point into IIS for custom Web Request handling
ISAPI (Internet Server Application Program Interface) is a set of Windows program (APIs (DLL)) calls that let you write a Web server application that will run faster than a common gateway interface (CGI) application.
Let's technically see this...
When the first ASP.NET request comes in the DLL will spawn a new process in another EXE – aspnet_wp.exe/w3wp.exe – and route processing to this spawned process. This process in turn loads and hosts the .NET runtime. Every request that comes into the ISAPI DLL then routes to this worker process via Named Pipe calls.
A request starts on the browser where the user types in a URL, clicks on a hyperlink or submits an HTML form. Or a client application might make call against an ASP.NET based Web Service, which is also serviced by ASP.NET. On the server side the Web Server IIS picks up the request. At the lowest level ASP.NET interfaces with IIS through an ISAPI extension.
In IIS .aspx is mapped through an 'Application Extension' (aka. as a script map) that is mapped to the ASP.NET ISAPI dll - aspnet_isapi.dll. Every request that fires ASP.NET must go through an extension that is registered and points at aspnet_isapi.dll.
ISAPI is very low level it also is very fast, but fairly unmanageable for application level development. So, ISAPI has been mainly relegated for some time to providing bridge interfaces to other application or platforms. But ISAPI isn't dead by any means. In fact, ASP.NET on Microsoft platforms interfaces with IIS through an ISAPI extension that hosts .NET and through it the ASP.NET runtime. ISAPI provides the core interface from the Web Server and ASP.NET uses the unmanaged ISAPI code to retrieve input and send output back to the client. The content that ISAPI provides is available via common objects like HttpRequest and HttpResponse that expose the unmanaged data as managed objects with a nice and accessible interface.
What Kind of HTTP Server Is Needed to Run ISAPI?
To host Web sites, you must have an Internet server that supports the Hypertext Transfer Protocol (HTTP). If you have chosen an ISAPI-compliant Web server (for example, Microsoft Internet Information Server), you can take advantage of server extension DLLs to create small, fast Internet server applications.
A special kind of ISAPI DLL is called an ISAPI filter, which can be designated to receive control for every HTTP request. You can create an ISAPI filter for encryption or decryption, for logging, for request screening, or for other purposes. 
ISAPI consists of two components: Extensions and FiltersThese are the only two types of application that can be developed using ISAPI. 
Extensions
ISAPI Extensions are true applications that run on IIS. They have access to all of the functionality provided by IIS. ISAPI extensions are implemented as DLLs that are loaded into a process that is controlled by IIS. Clients can access ISAPI extensions in the same way they access a static HTML page. 
Filters
ISAPI filters are used to modify or enhance the functionality provided by IIS. They always run on an IIS server and filter every request until they find one they need to process. Filters can be programmed to examine and modify both incoming and outgoing streams of data. 
Filters are implemented as DLL files and can be registered on an IIS server on a site level or a global level (i.e., apply to all sites on an IIS server). Filters are initialized when the worker process is started and listens to all requests to the site on which it is installed. 
Common tasks performed by ISAPI filters include:
  • Changing request data (URLs or headers) sent by the client
  • Controlling which physical file gets mapped to the URL
  • Controlling the user name and password used with anonymous or basic authentication
  • Modifying or analyzing a request after authentication is complete
  • Modifying a response going back to the client
  • Running custom processing on "access denied" responses
  • Running processing when a request is complete
  • Run processing when a connection with the client is closed
  • Performing special logging or traffic analysis.
  • Performing custom authentication.
  • Handling encryption and compression.
Example
Following are the main Server side scripting languages which support ISAPI.
  • ASP
  • ASP.NET
  • Perl
  • PHP 


Thursday, 7 March 2013

Gridview Edit Delete and Update in ASP.NET


Websites often display thousands of data in a GridView in ASP.Net. Usually admin can view the registered users on the website, but when an admin wants to edit or delete any fraud or duplicate or damaged data from the table there is a method in GridView to edit, delete and update. See the note section below.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;

}
</style>
<script type="text/javascript">

</script>
</head>
<body>
    <form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id"OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"OnRowUpdating="GridView1_RowUpdating">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="S.No." />
        <asp:BoundField DataField="name" HeaderText="Name" />
        <asp:BoundField DataField="address" HeaderText="address" />
        <asp:BoundField DataField="country" HeaderText="Country" />
        <asp:CommandField ShowEditButton="true" />
        <asp:CommandField ShowDeleteButton="true" />
        </Columns>
    </asp:GridView>

    </div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
    </form>
</body>
</html>
Design

The design part will look as in the following image:

GridView1.jpg

Code behind
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    private SqlConnection conn = new SqlConnection("Data Source=REDDYS-PC;Integrated Security=true;Initial Catalog=sample");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvbind();
            }
        }
        protected void gvbind()
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select * from detail", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            conn.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                GridView1.DataSource = ds;
                GridView1.DataBind();
                int columncount = GridView1.Rows[0].Cells.Count;
                GridView1.Rows[0].Cells.Clear();
                GridView1.Rows[0].Cells.Add(new TableCell());
                GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
                GridView1.Rows[0].Cells[0].Text = "No Records Found";
            }

        }      

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            Label lbldeleteid = (Label)row.FindControl("lblID");
            conn.Open();
            SqlCommand cmd = new SqlCommand("delete FROM detail where id='"+Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString())+"'", conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            gvbind();

        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            gvbind();
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            Label lblID = (Label)row.FindControl("lblID");
            //TextBox txtname=(TextBox)gr.cell[].control[];
            TextBox textName = (TextBox)row.Cells[0].Controls[0];
            TextBox textadd = (TextBox)row.Cells[1].Controls[0];
            TextBox textc = (TextBox)row.Cells[2].Controls[0];
            //TextBox textadd = (TextBox)row.FindControl("txtadd");
            //TextBox textc = (TextBox)row.FindControl("txtc");
            GridView1.EditIndex = -1;
            conn.Open();
            //SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
            SqlCommand cmd = new SqlCommand("update detail set name='"+textName.Text+"',address='"+textadd.Text+"',country='"+textc.Text+"'where id='"+userid+"'",conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            gvbind();
            //GridView1.DataBind();
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            gvbind();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            gvbind();
        }
}
Save all or press "Ctrl+S" and hit "F5" to run the page, the page will look as in the following image:

GridView2.jpg

Click on "Edit the GridView", it will display Textboxes in each cell as in the following image:

GridView3.jpg