Silverlight WebSockets – Duplex Communication

A duplex communication system is a system composed of two connected parties or devices that can communicate with one another in both directions. Duplex communication is required when you need to send some data in the reverse direction i.e. from Server to client. For scenario purpose assume that something happens on server (some event is received from source) and message from server should be sent to connected clients. Off-course the solution should be highly scalable with low latency client and server.

Let’s talk about silverlight client in our scenario

 There could be couple of options with silverlight client demonstrated by Gill Cleeren In series of article “The duplex story: looking at duplex communication in Silverlight 4

Silverlight 4.0 now supports 3 different types of duplex communications

  • HTTP Polling Duplex: Duplex requires that the server can itself initiate communication, which is not supported by HTTP, HTTP Polling duplex (HTTP long polling, or Comet-style) protocol allows us to do bi-directional communication over HTTP. What happens behind the scenes is the following:
    • The Silverlight client initiates the communication by sending an initial request to the service.
    • After the client is registered with the service, it continuously starts polling the service for updates.
    • Whenever the service has new messages to send to the client, they are queued up until a new poll arrives from the client.

The HTTP Polling Duplex is therefore not real duplexing: it creates an illusion of duplex communication by polling (at network layer) so frequently that it looks as if the messages are pushed from the service to the client. If you still want to use this method here is the link for you to tune performance of http polling duplex.

  • Sockets: Socket is implemented through the use of a TcpListener, Being pure TCP endpoints, sockets are fast and true duplex communicators. However sockets in Silverlight can only work over ports between 4502 and 4534 making it unsuitable for duplex communication over the internet. Secondly you need to build policy server to provide clientaccesspolicy.xml for sockets.Note that Silverlight 4 also allows that the policy calls are made over HTTP.
  • net.tcp binding: this entirely new binding, added in Silverlight 4, also supports duplex communication. net.tcp combines advantages of both polling duplex and sockets. Its programming model is, just like polling duplex, based on WCF. That means that we can take advantage of automatic proxy generation inside Visual Studio.
  • Poll based communication: Not scalable, out of scope.

So what’s next?

 HTML 5 – WebSockets

Web socket protocol or WebSockets are “TCP for the Web,” a next-generation bidirectional communication technology for web applications being standardized in part of Web Applications 1.0.

The Web Sockets API enables web applications to handle bidirectional communications with server-side process in a straightforward way. Once you get a Web Socket connection, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. The protocol is not raw TCP because it needs to provide the browser’s “same-origin” security model. It’s also not HTTP because web socket traffic differers from HTTP’s request-response model. you do need a new server implementation to communicate with web sockets .

web socket prototype is out now at or websocket msi from here

 for more information see :

Please also find the published websocket transport binding (Incomplete project)  here which i was trying to build using custom duplex WCF channel.

ASP.Net and Ajax

AJAX (Asynchronous JavaScript and XML) is arguably one of the most hyped technology acronyms around. The primary advantage of using AJAX is that page refreshes can be minimized, allowing users to get the information they need quickly and easily through a more rich and functional interface. Ajax accomplishes this by using JavaScript and an XmlHttp object to send data asynchronously from the browser to the Web server and back.

ASP.Net Ajax Extensions

Microsoft’s ASP.NET AJAX Extensions provide developers with a quick and simple way to add AJAX functionality into any ASP.NET Website, without requiring in-depth knowledge of JavaScript or other AJAX technologies.

Visual Studio 2008 and above by default have AJAX extensions installed or you may download from microsoft site.

Ajax Extension provides 3 controls named “Timer”, UpdatePanel and UpdateProgress you can implement partial page submit using updatepanels.

ASP.Net Ajax Control Toolkit

The ASP.NET AJAX Control Toolkit  is an open-source project built on top of the Microsoft ASP.NET AJAX framework. It is a joint effort between Microsoft and the ASP.NET AJAX community that provides a powerful infrastructure to write reusable, customizable and extensible ASP.NET AJAX extenders and controls, as well as a rich array of controls that can be used out of the box to create an interactive Web experience.

The Ajax Control Toolkit contains more than 40 controls, including the AutoComplete, CollapsiblePanel, ColorPicker, MaskedEdit, Calendar, Accordion, and Watermark controls.

Don’t miss to check all controls in online demo at ASP.Net control toolkit samples.

Note : With ASP.Net ajax toolkit it is possible to have combobox having long text inside list items but fixed size combobox control. Check your self in above link.

Microsoft has published huge learning contents including videos and articles , explore your self to learn Ajax toolkit here.

Configure ASP.Net Ajax Toolkit :

  1. Download the latest release of the Ajax Control Toolkit from CodePlex.
  2. Unzip binary contents.
  3. Add tab to toolbox and choose item -> browse -> locate : AjaxControlToolkit.dll

Note : You may encounter problems when trying to use the Ajax Control Toolkit for the first time. Ajax Control Toolkit needs to be setup using its script manager and not the standard Script Manager.So one way to avoid the above issues is to drag the ToolkitScriptManager (found in the control toolkit) onto the Form tag and then use any other Ajax Controls.

ASP.Net Basic

In this article we will explore the ASP.Net page events and stages which are part of page life cycle. Before we go ahead i would like to review what we have learnt so far in previous articles related to ASP.Net.

IIS: IIS (Internet Information Server) is a Microsoft Web server that makes it possible to quickly and easily deploy powerful Web sites and applications. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. (By default, ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.)


  • If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. It will be handled by the IIS. The requested page/image/file is returned without any processing.
  • If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application’s Web.config file.

ASPNET_ISAPI.DLL: This DLL is the ISAPI extension provided with ASP.NET to process the web page requests. IIS loads this DLL and sends the page request to this DLL. This DLL loads the HTTPRuntime for further processing.

ASPNET_WP.EXE: Each worker process (ASPNET_WP.EXE) contains an Application Pool. Each Application Pool can contain any number of Applications. Application Pool is also called as AppDomain. When a web page is requested, IIS looks for the application pool under which the current application is running and forwards the request to the respective worker process.

HTTP Pipeline: HTTP Pipeline is the general-purpose framework for server-side HTTP programming that serves as the foundation for ASP.NET pages as well as Web Services. All the stages involved from creating HTTP Runtime to HTTP Handler is called HTTP Pipeline.

HTTP Runtime: Each AppDomain has its own instance of the HttpRuntime class—the entry point in the pipeline. The HttpRuntime object initializes a number of internal objects that will help carry the request out. The HttpRuntime creates the context for the request and fills it up with any HTTP information specific to the request. The context is represented by an instance of the HttpContext class. Another helper object that gets created at such an early stage of the HTTP runtime setup is the text writer—to contain the response text for the browser. The text writer is an instance of the HttpWriter class and is the object that actually buffers any text programmatically sent out by the code in the page. Once the HTTP runtime is initialized, it finds an application object to fulfill the request. The HttpRuntime object examines the request and figures out which application it was sent to (from the pipeline’s perspective, a virtual directory is an application).

HTTP Context: This is created by HTTP Runtime. The HttpContext class contains objects that are specific to the current page request, such as the HttpRequest and HttpResponse objects. You can use this class to share information between pages. It can be accessed with Page.Context property in the code.

HTTP Request
: Provides access to the current page request, including the request headers, cookies, client certificate, query string, and so on. You can use this class to read what the browser has sent. It can be accessed with Page.Request property in the code.

HTTP Response: Provides access to the output stream for the current page. You can use this class to inject text into the page, to write cookies, and more. It can be accessed with Page.Response property in the code.

HTTP Application: An application object is an instance of the HttpApplication class—the class behind the global.asax file. HTTPRuntime uses HttpApplicationFactory to create the HTTPApplication object. The main task accomplished by the HTTP application manager is finding out the class that will actually handle the request. When the request is for an .aspx resource, the handler is a page handler—namely, an instance of a class that inherits from Page. The association between types of resources and types of handlers is stored in the configuration file of the application. More exactly, the default set of mappings is defined in the <httpHandlers> section of the machine.config file. However, the application can customize the list of its own HTTP handlers in the local web.config file. The line below illustrates the code that defines the HTTP handler for .aspx resources.

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>

HttpApplicationFactory: Its main task consists of using the URL information to find a match between the virtual directory of the URL and a pooled HttpApplication object.

HTTP Module: An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request. They also let you examine the outgoing response and modify it. ASP.NET uses modules to implement various application features, which include forms authentication, caching, session state, and client script services. In each case, when those services are enabled, the module is called as part of a request and performs tasks that are outside the scope of any single page request. Modules can consume application events and can raise events that can be handled in the Global.asax file.

HTTP Handler: An ASP.NET HTTP handler is the process that runs in response to a request that is made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request a .aspx file, the request is processed by the page handler. We can write our own handler and handler factory if we want to handle the page request in a different manner.

Note: HTTP modules differ from HTTP handlers. An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.

In brief, here is the explanation of what happen to request when it arries at IIS

  • Web page request comes from browser.
  • IIS maps the ASP.NET file extensions to ASPNET_ISAPI.DLL, an ISAPI extension provided with ASP.NET.
  • ASPNET_ISAPI.DLL forwards the request to the ASP.NET worker process (ASPNET_WP.EXE or W3P.EXE).
  • ISAPI loads HTTPRuntime and passes the request to it. Thus, HTTP Pipelining has begun.
  • HTTPRuntime uses HttpApplicationFactory to either create or reuse the HTTPApplication object.
  • HTTPRuntime creates HTTPContext for the current request. HTTPContext internally maintains HTTPRequest and HTTPResponse
  • HTTPRuntime also maps the HTTPContext to the HTTPApplication which handles the application level events.
  • HTTPApplication runs the HTTPModules for the page requests.
  • HTTPApplication creates HTTPHandler for the page request. This is the last stage of HTTPipelining.
  • HTTPHandlers are responsible to process request and generate corresponding response messages.
  • Once the request leaves the HTTPPipeline, page level events begin.
  • Page Events like load etc happens at this stage.
  • HTTPHandler generates the response with the above events and sends back to the IIS which in turn sends the response to the client browser.

ASP.Net page life cycle

ASP.Net page life cycle and stages involved several page stages and page events when it was triggered by HTTPHandler.Please not that there are Application stages which occurs before and after page life cycle which are discussed here.


Page goes through the several stages mentioned below alone with the description of each stage.

Stages Description
Page request The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
Start In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.
Initialization During page initialization, controls on the page are available and each control’s UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Postback event handling If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Rendering Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page’s Response property.
Unload The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.


Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.

Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true, page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Server Control Event Model.

Below are the page life-cycle events that you will use most frequently..

Page Event Typical Use
PreInit Raised after the start stage is complete and before the initialization stage begins.Use this event for the following:

  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.

NoteNote :  If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.Use this event to read or initialize control properties.
InitComplete Raised at the end of the page’s initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.Use this event to make changes to view state that you want to make sure are persisted after the next postback.
PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.Use the OnLoad event method to set properties in controls and to establish database connections.
Control events Use these events to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.

NoteNote : In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete Raised at the end of the event-handling stage.Use this event for tasks that require that all other controls on the page be loaded.
PreRender Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
PreRenderComplete Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup to send to the browser.If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload Raised for each control and then for the page.In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

NoteNote : During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.


Those who want to go in depth study for life cycle events may explore msdn where you will find more than enough information what you are looking for.The next article “All about patterns” of this series is bit different in the sequence of the series i was writing under .Net Concepts category on this blog.

In next my next article”All about patterns” i would like to take the opportunity to explore different kind of patterns and further series will include in depth study of MVC and MVVM architectural patterns.Once we finished pattern series we will further explore internals and other features.

ASP.Net Internals

In the previous article IIS 6.0 article we have learnt how IIS routes web request to ASP.Net ISAPI “aspnet_isapi.dll“.In this article we will looks at find how web requests flow through the ASP.NET framework , from Web Server, through ISAPI all the way up the request handler and your code.ISAPI is a low level unmanged Win32 API. The interfaces defined by the ISAPI spec are very simplistic and optimized for performance. They are very low level – dealing with raw pointers and function pointer tables for callbacks – but they provide he lowest and most performance oriented interface that developers and tool vendors can use to hook into IIS.ISAPI tends to be used primarily as a bridge interface to provide Application Server type functionality to higher level tools. For example, ASP and ASP.NET both are layered on top of ISAPI. 

As a protocol ISAPI supports both ISAPI extensions and ISAPI Filters. Extensions are a request handling interface and provide the logic to handle input and output with the Web Server – it’s essentially a transaction interface. ASP and ASP.NET are implemented as ISAPI extensions. ISAPI filters are hook interfaces that allow the ability to look at EVERY request that comes into IIS and to modify the content or change the behavior of functionalities like Authentication. Incidentally ASP.NET maps ISAPI-like functionality via two concepts: Http Handlers (extensions) and Http Modules (filters). We’ll look at these later in more detail. 

IIS (5.0, 6.0) and ASP.Net 

  In IIS 5 hosts aspnet_isapi.dll directly in the inetinfo.exe process or one of its isolated worker processes (as discussed in previous article).While processing the Web Requests,IIS picks up the request and forwards the request to aspnet_isapi.dll. After that it is forwarded to the Worker process (asp_wp.exe) via Named Pipe calls.Worker process manages the pipeline through request flows. All software components like HttpApplication, Session run by the instance of Worker Process. 

In case of IIS 6.0 the request is processed by HTTP.SYS driver and then passed to the worker process. HTTP.SYS is a kernel level driver close to operating system. By passing the request directly to worker process, bypass the overhead of an extra out-of-process call and automatically enforces application isolation. 

With IIS 5.0 then applications are pooled in one application pool which is hosted by DLLHost.exe. But in case of IIS 6.0 where IIS 6.0 operates in worker process isolation mode, up to 2000 application pools can be created where each application pool can be configured separately. 

In IIS 6.0, ISAPI extensions run in the application pool worker process. The .NET Runtime also runs in this same process, so communication between the ISAPI extension and the .NET runtime happens in-process which is inherently more efficient than the named pipe interface that IIS 5 must use. 

ASP.Net Worker Process 

The worker processes ASPNET_WP.EXE (IIS5) and W3WP.EXE (IIS6) host the .NET runtime and the ISAPI DLL calls into small set of unmanged interfaces via low level COM that eventually forward calls to an instance subclass of the ISAPIRuntime class. The first entry point to the runtime is the undocumented ISAPIRuntime class which exposes the IISAPIRuntime interface via COM to a caller.To create the ISAPIRuntime instance the System.Web.Hosting.AppDomainFactory.Create() method is called when the first request for a specific virtual directory is requested. This starts the ‘Application’ bootstrapping process. The call receives parameters for type and module name and virtual path information for the application which is used by ASP.NET to create an AppDomain and launch the ASP.NET application for the given virtual directory. This HttpRuntime derived object is created in a new AppDomain. Each virtual directory or ASP.NET application is hosted in a separate AppDomain and they get loaded only as requests hit the particular ASP.NET Application. The ISAPI extension manages these instances of the HttpRuntime objects, and routes inbound requests to the right one based on the virtual path of the request. 

At this point we have an instance of ISAPIRuntime active and callable from the ISAPI extension. Once the runtime is up and running the ISAPI code calls into the ISAPIRuntime.ProcessRequest() method which is the real entry point into the ASP. 

Note : Remember ISAPI is multi-threaded so requests will come in on multiple threads through the reference that was returned by ApplicationDomainFactory.Create(). 

HttpRuntime, HttpContext, and HttpApplication 

When a request hits, it is routed to the ISAPIRuntime.ProcessRequest() method. This method in turn calls HttpRuntime.ProcessRequest that does several important things (look at System.Web.HttpRuntime.ProcessRequestInternal with Reflector): 

  • Create a new HttpContext instance for the request
  • Retrieves an HttpApplication Instance
  • Calls HttpApplication.Init() to set up Pipeline Events
  • Init() fires HttpApplication.ResumeProcessing() which starts the ASP.NET pipeline processing

First a new HttpContext object is created and it is passed the ISAPIWorkerRequest that wrappers the ISAPI ECB. The Context is available throughout the lifetime of the request and ALWAYS accessible via the static HttpContext.Current property. As the name implies, the HttpContext object represents the context of the currently active request as it contains references to all of the vital objects you typically access during the request lifetime: Request, Response, Application, Server, Cache. At any time during request processing HttpContext.Current gives you access to all of these object. 

The HttpContext object also contains a very useful Items collection that you can use to store data that is request specific. The context object gets created at the begging of the request cycle and released when the request finishes, so data stored there in the Items collection is specific only to the current request. A good example use is a request logging mechanism where you want to track start and end times of a request by hooking the Application_BeginRequest and Application_EndRequest methods in Global.asax. 

Once the Context has been set up, ASP.NET needs to route your incoming request to the appropriate application/virtual directory by way of an HttpApplication object. Every ASP.NET application must be set up as a Virtual (or Web Root) directory and each of these ‘applications’ are handled independently. 

Each request is routed to an HttpApplication object. The HttpApplicationFactory class creates a pool of HttpApplication objects for your ASP.NET application depending on the load on the application and hands out references for each incoming request. The size of the pool is limited to the setting of the MaxWorkerThreads setting in machine.config’s ProcessModel Key, which by default is 20. 

The pool starts out with a smaller number though; usually one and it then grows as multiple simulataneous requests need to be processed. The Pool is monitored so under load it may grow to its max number of instances, which is later scaled back to a smaller number as the load drops. 

HttpApplication is the outer container for your specific Web application and it maps to the class that is defined in Global.asax. It’s the first entry point into the HTTP Runtime that you actually see on a regular basis in your applications. If you look in Global.asax (or the code behind class) you’ll find that this class derives directly from HttpApplication. 

HttpApplication’s primary purpose is to act as the event controller of the Http Pipeline and so its interface consists primarily of events. The event hooks are extensive and include: 

  • BeginRequest
  • AuthenticateRequest
  • AuthorizeRequest
  • ResolveRequestCache
  • AquireRequestState
  • PreRequestHandlerExecute
  • Handler Execution
  • PostRequestHandlerExecute
  • eleaseRequestState
  • UpdateRequestCache
  • EndRequest

Each of these events are also implemented in the Global.asax file via empty methods that start with an Application_ prefix. For example, Application_BeginRequest(), Application_AuthorizeRequest(). These handlers are provided for convenience since they are frequently used in applications and make it so that you don’t have to explicitly create the event handler delegates. 

It’s important to understand that each ASP.NET virtual application runs in its own AppDomain and that there inside of the AppDomain multiple HttpApplication instances running simultaneously, fed out of a pool that ASP.NET manages. This is so that multiple requests can process at the same time without interfering with each other. 

AppDomain ID stays steady while thread and HttpApplication Ids change on most requests, although they likely will repeat. HttpApplications are running out of a collection and are reused for subsequent requests so the ids repeat at times. Note though that Application instance are not tied to a specific thread – rather they are assigned to the active executing thread of the current request. 

Threads are served from the .NET ThreadPool and by default are Multithreaded Apartment (MTA) style threads. You can override this apartment state in ASP.NET pages with the ASPCOMPAT=”true” attribute in the @Page directive. ASPCOMPAT is meant to provide COM components a safe environment to run in and ASPCOMPAT uses special Single Threaded Apartment (STA) threads to service those requests. STA threads are set aside and pooled separately as they require special handling. 

Since HttpApplication objects are all running in the same AppDomain ,thi is how ASP.NET can guarantee that changes to web.config or individual ASP.NET pages get recognized throughout the AppDomain. Making a change to a value in web.config causes the AppDomain to be shut down and restarted. This makes sure that all instances of HttpApplication see the changes made because when the AppDomain reloads the changes from ASP.NET are re-read at startup. Any static references are also reloaded when the AppDomain so if the application reads values from App Configuration settings these values also get refreshed. 

Any requests that are already in the pipeline processing will continue running through the existing pipeline, while any new requests coming in are routed to the new AppDomain. In order to deal with ‘hung requests’ ASP.NET forcefully shuts down the AppDomain after the request timeout period is up even if requests are still pending. So it’s actually possible that two AppDomains exist for the same HttpApplication at a given point in time as the old one’s shutting down and the new one is ramping up. Both AppDomains continue to serve their clients until the old one has run out its pending requests and shuts down leaving just the new AppDomain running. 

HttpContext, HttpModules and HttpHandlers 

The HttpApplication itself knows nothing about the data being sent to the application – it is a merely messaging object that communicates via events. It fires events and passes information via the HttpContext object to the called methods. The actual state data for the current request is maintained in the HttpContext object mentioned earlier. It provides all the request specific data and follows each request from beginning to end through the pipeline.Once the pipeline is started, HttpApplication starts firing events one by one.Each of the event handlers is fired and if events are hooked up those handlers execute and perform their tasks. The main purpose of this process is to eventually call the HttpHandler hooked up to a specific request. Handlers are the core processing mechanism for ASP.NET requests and usually the place where any application level code is executed. Remember that the ASP.NET Page and Web Service frameworks are implemented as HTTPHandlers and that’s where all the core processing of the request is handled. Modules tend to be of a more core nature used to prepare or post process the Context that is delivered to the handler. Typical default handlers in ASP.NET are Authentication, Caching for pre-processing and various encoding mechanisms on post processing. 

HTTP modules and HTTP handlers are an integral part of the ASP.NET architecture. While a request is being processed, each request is processed by multiple HTTP modules (for example, the authentication module and the session module) and is then processed by a single HTTP handler. After the handler has processed the request, the request flows back through the HTTP modules. Each module receives the http request and has full control over it. The module can play with the request in any way it sees fit. Once the request passes through all of the HTTP modules, it is eventually served by an HTTP handler. The HTTP handler performs some processing on it, and the result again passes through the HTTP modules in the pipeline. 

To create an HTTP module, you must implement the IHttpModule interface in you class and add module in web.config as mentioned below 

   <add type="[COM+ Class], [Assembly]" name="[ModuleName]" />
   <remove type="[COM+ Class], [Assembly]" name="[ModuleName]" />
   <clear />

HTTPHandlers are used to process individual endpoint requests. Handlers enable the ASP.NET framework to process individual HTTP URLs or groups of URL extensions within an application. Unlike modules, only one handler is used to process a request. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions. 

ASP.NET uses HTTP handlers for implementing a lot of its own functionality. ASP.NET uses handlers for processing .aspx, .asmx, .soap and other ASP.NET files. 

The following is the snippet from the machine.config fileYou can see in the above configuration that all the requests for .aspx files are processed by the System.Web.UI.PageHandlerFactory class. Similarly all the requests for .config and other files, which should not be directly accessible to the clients, are handled by the System.Web.HttpForbiddenHandler class. As you might have already guessed, this class simply returns an error to the client stating that these kinds of files are not served. 

<add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler"/>
 <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>
 <add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory"/>
 <add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler"/>
  <add verb="GET,HEAD" path="*" type="System.Web.StaticFileHandler"/>
  . . . . . .
 . . . . . .

 You might be thinking about the use of such a handler. Well, what if you want to introduce a new kind of server scripting language or dynamic server file such as asp, aspx? You can write your own handler for this.

To implementing  HTTP handler following steps are required

  • Write a class which implements IHttpHandler interface
  • Register this handler in web.config or machine.config file.
  • Map the file extension (.aspx) to ASP.NET ISAPI extension DLL (aspnet_isapi.dll) in Internet Services Manager.

Maintaining session state is one of the most common tasks that Web applications perform. HTTP handlers also need to have access to the session state. But session state is not enabled by default for HTTP handlers. In order to read and/or write session data, HTTP handlers are required to implement one of the following interfaces:

  • IRequiresSessionState
  • IReadOnlySessionState.

An HTTP handler should implement the IRequiresSessionState interface when it requires read-write access to the session data. If a handler only needs read access to session data, then it should only implement the IReadOnlySessionState interface.

In the next article of this series we will learn ASP.Net Basic..