Tuesday, August 23, 2011

Process Request using MHPM Events Fired

Once ‘HttpApplication’ is created, it starts processing requests. It goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections, it invokes different events which the developer can extend and add customize logic to the same.
Before we move ahead, let's understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:
  • If you want to inject logic based in file extensions like ‘.ASPX’, ‘.HTML’, then you use ‘HttpHandler’. In other words, ‘HttpHandler’ is an extension based processor.
  • If you want to inject logic in the events of ASP.NET pipleline, then you use ‘HttpModule’. ASP.NET. In other words, ‘HttpModule’ is an event based processor.

You can read more about the differences from here.
Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below:

Step 1(M: HttpModule): Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET HttpModule emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created BeginRequest, AuthenticateRequest, AuthorizeRequest, ResolveRequestCache, AcquireRequestState and PreRequestHandlerExecute.

Step 2 (H: ‘HttpHandler’): Once the above 6 events are fired, ASP.NET engine will invoke ProcessRequest event if you have implemented HttpHandler in your project.

Step 3 (P: ASP.NET page): Once the HttpHandler logic executes, the ASP.NET page object is created. While the ASP.NET page object is created, many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages Init, Load, validate, event, render and unload. You can remember the word SILVER to remember the events S – Start (does not signify anything as such just forms the word) , I – (Init) , L (Load) , V (Validate), E (Event) and R (Render).

Step4 (M: HttpModule): Once the page object is executed and unloaded from memory, HttpModule provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events PostRequestHandlerExecute, ReleaserequestState, UpdateRequestCache and EndRequest.
The below figure shows the same in a pictorial format.


In What Event Should We Do What?

The million dollar question is in which events should we do what? Below is the table which shows in which event what kind of logic or code can go.

Section
Event
Description
HttpModule
BeginRequest
This event signals a new request; it is guaranteed to be raised on each request.
HttpModule
AuthenticateRequest
This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.
HttpModule
AuthorizeRequest
This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.
HttpModule
ResolveRequestCache
In ASP.NET, we normally use outputcache directive to do caching. In this event, ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.
HttpModule
AcquireRequestState
This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.
HttpModule
PreRequestHandlerExecute
This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.
HttpHandler
ProcessRequest
Httphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.
Page
Init
This event happens in the ASP.NET page and can be used for:
  • Creating controls dynamically, in case you have controls to be created on runtime.
  • Any setting initialization.
  • Master pages and the settings.

In this section, we do not have access to viewstate, postedvalues and neither the controls are initialized.
Page
Load
In this section, the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Page
Validate
If you have valuators on your page, you would like to check the same here.
Render
It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser, you can enter your HTML logic here.
Page
Unload
Page object is unloaded from the memory.
HttpModulePostRequestHandlerExecute
Any logic you would like to inject after the handlers are executed.
HttpModule
ReleaserequestState
If you would like to save update some state variables like session variables.
HttpModule
UpdateRequestCache
Before you end, if you want to update your cache.
HttpModule
EndRequest
This is the last stage before your output is sent to the client browser.


for more information take a look at code project.

Creation of ASP.NET Environment

Step 1: The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance, if the page is an ‘.ASPX page’, then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2: If this is the first request to the website, then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know, the application domain creates isolation between two web applications hosted on the same IIS. So in case there is an issue in one app domain, it does not affect the other app domain.

Step 3: The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4: Once all the core ASP.NET objects are created, ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system, then the object of the ‘global.asax’ file will be created. Please note global.asax file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, HttpApplication instances might be reused for multiple requests.

Step 5: The HttpApplication object is then assigned to the core ASP.NET objects to process the page.

Step 6: HttpApplication then starts processing the request by HTTP module events, handlers and page events. It fires the MHPM event for request processing.



The below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.



main article from code project

The two step process request

From 30,000 feet level, ASP.NET request processing is a 2 step process as shown below. User sends a request to the IIS:
  • ASP.NET creates an environment which can process the request. In other words, it creates the application object, request, response and context objects to process the request.
  • Once the environment is created, the request is processed through a series of events which is processed by using modules, handlers and page objects. To keep it short, let's name this step as MHPM (Module, handler, page and Module event), we will come to details later.

main article from code project

Tuesday, August 9, 2011

Explain the life cycle of an ASP .NET page.?

Following are the events occur during ASP.NET Page Life Cycle:

1)Page_PreInit
2)Page_Init
3)Page_InitComplete
4)Page_PreLoad
5)Page_Load
6)Control Events
7)Page_LoadComplete
8)Page_PreRender
9)SaveViewState
10)Page_Render
11)Page_Unload

What are the different ClientIDModes we can set and how will they work?

The new ClientIDMode property lets you specify more precisely how the client ID is generated for controls. You can set the ClientIDMode property for any control, including for the page. Possible settings are the following:
AutoID
This is equivalent to the algorithm for generating ClientID property values that was used in earlier versions of ASP.NET.

Static
This specifies that the ClientID value will be the same as the ID without concatenating the IDs of parent naming containers. This can be useful in Web user controls. Because a Web user control can be located on different pages and in different container controls, it can be difficult to write client script for controls that use the AutoID algorithm because you cannot predict what the ID values will be.

Predictable
This option is primarily for use in data controls that use repeating templates. It concatenates the ID properties of the control's naming containers, but generated ClientID values do not contain strings like "ctlxxx". This setting works in conjunction with the ClientIDRowSuffix property of the control. You set the ClientIDRowSuffix property to the name of a data field, and the value of that field is used as the suffix for the generated ClientID value. Typically you would use the primary key of a data record as the ClientIDRowSuffix value.

Inherit
This setting is the default behavior for controls; it specifies that a control's ID generation is the same as its parent.

How do you implement ViewState for a control?

In ASP.NET 4, Web server controls include a ViewStateMode property that lets you disable view state by default and then enable it only for the controls that require it in the page.
The ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit. Enabled enables view state for that control and for any child controls that are set to Inherit or that have nothing set. Disabled disables view state, and Inherit specifies that the control uses the ViewStateMode setting from the parent control.


<asp:PlaceHolder ID="PlaceHolder1" runat="server" ViewStateMode="Disabled">
Disabled: <asp:Label ID="label1" runat="server" Text="[DeclaredValue]" /><br />
<asp:PlaceHolder ID="PlaceHolder2" runat="server" ViewStateMode="Enabled">
Enabled: <asp:Label ID="label2" runat="server" Text="[DeclaredValue]" />
</asp:PlaceHolder>
</asp:PlaceHolder>

what is the difference between application state and caching?

Application Object and Cached Object both falls under Server side State Management.

Application object resides in InProc i.e. on the same server where we hosted our application.
Cache Object resides on server side/ DownStream/Client Side.

Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.

Only one user can access Application Object at a time hence we have to lock it every time we modify it.

Can User Control be stored in library?.

I will say "NO"

there are 3 types of controls:
1) User Control
2) Custom Control
3) Web parts

you can reuse User control in the current project in which you have built it, but you can't move it to other project as unless you just copy paste the same file there and make the changes for that project ( which violets the concept of library).

but custom control can be shared between projects. and you can precompile them even as a dll, so this means you can use them in library of any type.

What are the uses of Reflection??

Reflection is a concept using which we can

1) Load assemblies dynamically
2) Invoke methods at runtime
3) Retriving type information at runtime.

Where do the Cookie State and Session State information be stored?

Cookie Information will be stored in a txt file on client system under a
folder named Cookies. Search for it in your system you will find it.

Coming to Session State
As we know for every process some default space will be allocated by OS.

In case of InProc Session Info will be stored inside the process where our
application is running.
In case of StateServer Session Info will be stored using ASP.NET State Service.
In case of SQLServer Session info will be stored inside Database. Default DB
which will be created after running InstallSQLState Script is ASPState.

What is the difference between Response.Redirect and Server.Transfer.

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server.Server.Transfer does not update the clients url history list or current url.

Response.Redirect is used toredirect the user's browser to another page or site. This performs a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

What is the exact purpose of http handlers?

ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP URLs or groups of URL extensions within an application. HttpHandlers have the same functionality as ISAPI extensions with a much simpler programming model

Ex
1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)
2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler (*.asmx)

An HttpHandler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler usually launches a process that can be lengthy and returns before that process finishes
After writing and compiling the code to implement an HttpHandler you must register the handler using your application's Web.config file.

Is there any limit for query string? means what is the maximum size?..

Servers should be cautious about depending on URI lengths above 255 bytes because some older client or proxy implementations may not properly support these lengths.

Query string length depends on browser compatability

IE supports upto 255
Firefox supports upto 4000

Monday, August 8, 2011

How do you implement custom output caching?

Create a custom output-cache provider as a class that derives from the new System.Web.Caching.OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown below:
              

<caching>
<outputCache defaultProvider="AspNetInternalProvider">
<providers>
<add name="DiskCache"
type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/>
</providers>
</outputCache>
</caching>


Then specify the newly created and configured custom cache provider as below:

<%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %>


How is Caching extended in asp.Net 4.0?

OutPut Cache in earlier versions of ASP.Net has a limitation - generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.

ASP.NET 4 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines.

What is new in Asp.Net 4.0?

ASP.Net 4.0 has many improvements from previous versions such as
  • Web.config File Refactoring
  • Extensible Output Caching
  • Auto-Start Web Applications
  • Permanently Redirecting a Page by introducing a new method RedirectPermanent()
  • Shrinking Session State to shrink session data
  • Extensible Request Validation to avoid cross-site scripting (XSS) attacks by adding custom request-validation logic.
  • Object Caching and Object Caching Extensibility by introducing a new assembly "System.Runtime.Caching.dll"

ASP.Net 4.0 also introduced many new features such as
  • jQuery Included with Web Forms and MVC: Built in JQuery support
  • Content Delivery Network Support: Enables you to easily add ASP.NET Ajax and jQuery scripts to your Web applications. We can refence JQuery script over http like