Rajnish Noonia

Author: Pixytech

  • Introduction to Design Patterns

    A pattern describes a recurring problem that occurs in a given context and, based on a set of guiding forces, recommends a solution. The solution is usually a simple mechanism, a collaboration between two or more data objects, services, processes, threads, components, or nodes that work together to resolve the problem identified in the pattern.

    Mainly, there are three levels of patterns :

    • Design Patterns (e.g. GoF patterns)
    • Architectural Patterns (e.g. Layers, MVC,MVP,MVVM, P2P )
    • Implementation patterns (Idioms) (e.g. language specific patterns like Pimpl, RAII in C++)

    In my previous article “Design Patterns” we have discussed about Design Patterns,I will briefly re-define then in this article and will discuss Architectural patterns specifically MVC,MVP and MVVM patterns and their implementation.At the end of this article i will take you to Microsoft Enterprise Library (applications blocks) version 5.0 which was recently released (April 2010) and will also discuss about few guidance from microsoft like Composite Application Guidance (CAG).

    Design Patterns

    The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. The authors Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides are often referred to as the GoF, or Gang of Four.

    They are categorized in three groups:

    • Creational
    • Structural and
    • Behavioral

    Lets discuss them in brief (for detail please visti my previous article “Design Patterns“)

    • Creational Patterns
      • Abstract Factory : Creates an instance of several families of classes.
      • Builder :  Separates object construction from its representation.
      • Factory Method :  Creates an instance of several derived classes.
      • Prototype  :  A fully initialized instance to be copied or cloned.
      • Singleton  :  A class of which only a single instance can exist.
    • Structural Patterns
      • Adapter : Match interfaces of different classes.
      • Bridge :  Separates an object’s interface from its implementation.
      • Composite :  A tree structure of simple and composite objects.
      • Decorator :  Add responsibilities to objects dynamically.
      • Facade :  A single class that represents an entire subsystem.
      • Flyweight :  A fine-grained instance used for efficient sharing.
      • Proxy :  An object representing another object.
    • Behavioral Patterns
      • Chain of Resp. :  A way of passing a request between a chain of objects.
      • Command  :  Encapsulate a command request as an object.
      • Interpreter  : A way to include language elements in a program.
      • Iterator : Sequentially access the elements of a collection.
      • Mediator : Defines simplified communication between classes.
      • Memento : Capture and restore an object’s internal state.
      • Observer :  A way of notifying change to a number of classes.
      • State : Alter an object’s behavior when its state changes.
      • Strategy : Encapsulates an algorithm inside a class.
      • Template Method : Defer the exact steps of an algorithm to a subclass.
      • Visitor : Defines a new operation to a class without change.

    Architectural Patterns

    An Architectural Pattern expresses a fundamental structural organization or schema for software systems. It provides a set of predefined subsystems, specifies their responsibilities, and includes rules and guidelines for organizing the relationships between them.

    Model View Controller (MVC), Model View Presenter (MVP) , Model View ViewModel (MVVM) falls under architectural pattern, to be more precise they are architectural presentation patterns. In this article we will discuss about MVC, MVP and MVVM and their implementation using .net c#. There are other patterns like Application Architecture Pattern (Client-Proxy Server,Customer Support,Reactor,Replicated Servers,Layered Architecture, Pipe and Filter Architecture … and so on ) which are not discussed here.

    Model View Controller (MVC)

    Model-View-Controller (MVC) is a architectural Patternoften used by applications that need the ability to maintain multiple views of the same data. The MVC pattern hinges on a clean separation of objects into one of three categories — models for maintaining data, views for displaying all or a portion of the data, and controllers for handling events that affect the model or view(s).

    Because of this separation, multiple views and controllers can interface with the same model. Even new types of views and controllers that never existed before can interface with a model without forcing a change in the model design.

    It is important to note that both the view and the controller depend on the model. However, the model depends on neither the view nor the controller. This is one the key benefits of the separation. This separation allows the model to be built and tested independent of the visual presentation. The separation between view and controller is secondary in many rich-client applications, and, in fact, many user interface frameworks implement the roles as one object. In Web applications, on the other hand, the separation between view (the browser) and controller (the server-side components handling the HTTP request) is very well defined.

    Impelmenting MVC

    Microsoft has published ASP.NET MVC Framework if you want to use MVC in your web porject.

    The Model-View-Controller (MVC) pattern is an architectural design principle that separates the components of a Web application. This separation gives you more control over the individual parts of the application, which lets you more easily develop, modify, and test them.

    ASP.NET MVC is part of the ASP.NET framework. Developing an ASP.NET MVC application is an alternative to developing ASP.NET Web Forms pages; it does not replace the Web Forms model.

    Scott Gu says “If you are looking to build your web applications using a MVC approach, I think you’ll find this new ASP.NET MVC Framework option very clean and easy to use.  It will enable you to easily maintain separation of concerns in your applications, as well as facilitate clean testing and TDD.” Scott has written a series of blog posts on this new addition to the ASP.NET family. Read them:

    Note: However, please do not blindly use MVC pattern for each and every website that you create. Like most of the design Patterns, the MVC has its own disadvantages like performance hits and writing extra code.Make sure you dont take the pain without a reason.

    Again, MVC model is only an additional model/approach to develop ASP.NET applications and not a replacement for the existing rendering ASP.NET framework.

    When to Create an MVC Application

    You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.)

    Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.

    Advantages of an MVC-Based Web Application

    The ASP.NET MVC framework offers the following advantages

    • It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
    • It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
    • It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller.
    • It provides better support for test-driven development (TDD).
    • It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

    Advantages of a Web Forms-Based Web Application

    The Web Forms-based framework offers the following advantages:

    • It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
    • It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller.
    • It uses view state on server-based forms, which can make managing state information easier.
    • It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
    • In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.

    I would like to discuss about ASP.Net MVC in separate dedicated article, for the time being you may explore the contents published by microsoft.

    Note : Because ASP.NET MVC does not maintain state information by using view state, you must find other ways to manage state information, if you need it. In addition, server controls that rely on view state and postback will not work as designed in an ASP.NET MVC application. Therefore, you should not use controls such as the GridView, Repeater, and DataList controls.

    Model View Presenter (MVP)

    MVP is a derivative of MVC, mostly aimed at addressing the “Application Model” portion of MVC and focusing around the observer implementation in the MVC triad. Instead of a Controller, we now have a Presenter, but the basic idea remains the same – the model stores the data, the view is a representation of that data (not necessarily graphical), and the presenter coordinates the application.

    Separate the responsibilities for the visual display and the event handling behavior into different classes named, respectively, the view and the presenter. The view class  manages the controls on the page and it forwards user events to a presenter class. The presenter contains the logic to respond to the events, update the model (business logic and data of the application) and, in turn, manipulate the state of the view.

    To facilitate testing the presenter, make the presenter have a reference to the view interface instead of to the concrete implementation of the view. By doing this, you can easily replace the real view with a mock implementation to run tests.

    When the model is updated, the view also has to be updated to reflect the changes. View updates can be handled in several ways. The Model-View-Presenter variants, Passive View and Supervising Controller, specify different approaches to implementing view updates.

    In Passive View, the presenter updates the view to reflect changes in the model. The interaction with the model is handled exclusively by the presenter; the view is not aware of changes in the model.

    In Supervising Controller, the view interacts directly with the model to perform simple data-binding that can be defined declaratively, without presenter intervention. The presenter updates the model; it manipulates the state of the view only in cases where complex UI logic that cannot be specified declaratively is required.

    The decision to use Passive View or Supervising Controller primarily depends on how testable you want your application to be. If testability is a primary concern in your application, Passive View might be more suitable because you can test all the UI logic by testing the presenter. On the other hand, if you prefer code simplicity over full testability, Supervising Controller might be a better option because, for simple UI changes, you do not have to include code in the presenter that updates the view. When choosing between Passive View and Supervising Controller, consider the following:

    • Both variants allow you to increase the testability of your presentation logic.
    • Passive View usually provides a larger testing surface than Supervising Controller because all the view update logic is placed in the presenter.
    • Supervising Controller typically requires less code than Passive View because the presenter does not perform simple view updates.

    You can implement the interaction with the model in several ways. For example, you can implement the Observer pattern. This means that the presenter receives events from the model and updates the view as required. You may explore the Observer pattern in this artcile.

    MVC vs MVP

    • With MVC, it’s always the controller’s responsibility to handle mouse and keyboard events.
    • With MVP, GUI components themselves initially handle the user’s input, but delegate to the interpretation of that input to the presenter.
    • In modern GUI systems, GUI components themselves handle user input such as mouse movements and clicks, rather than some central controller. Thus MVP pattern is widely used in WinForms, .NET SmartClient Factory, etc.
    • In most web architectures, the MVC pattern is used (e.g. Struts, ASP.NET MVC etc)
    • MVP is a derivative of MVC, mostly aimed at addressing the “Application Model” portion of MVC and focusing around the observer implementation in the MVC triad. Instead of a Controller, we now have a Presenter, but the basic idea remains the same – the model stores the data, the view is a representation of that data (not necessarily graphical), and the presenter coordinates the application.
    • In MVP the Presenter gets some extra power. It’s purpose is to interpret events and perform any sort of logic necessary to map them to the proper commands to manipulate the model in the intended fashion. Most of the code dealing with how the user interface works is coded into the Presenter, making it much like the “Application Model” in the MVC approach.

    Presentation Model (PM)

    Model View ViewModel (MVVM)

    Continues with article “All About MVVM

  • 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.)

    Note:

    • 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.

    Stages

    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.

     Events

    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 asp.net 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 asp.net 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 asp.net worker process. HTTP.SYS is a kernel level driver close to operating system. By passing the request directly to asp.net worker process, asp.net 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 

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

    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. 

    <httpHandlers>
    <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"/>
      . . . . . .
     . . . . . .
    </httpHandlers>
    

     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..

  • IIS 6.0 Architecture

    Internet Information Services (IIS) – formerly called Internet Information Server – is a web server application and set of feature extension modules created by Microsoft for use with Microsoft Windows. IIS have several version and widely used are 6.0,7.0 and 7.5.Here,in this article i will try to explain IIS6 internals and its relation with ASP.Net.

    HTTP.sys (HTTP Protocol Stack)

    The HTTP listener is implemented as a kernel-mode device driver called the HTTP protocol stack (HTTP.sys). IIS 6.0 uses HTTP.sys, which is part of the networking subsystem of the Windows operating system, as a core component to receive and serve HTTP requests. Earlier versions of IIS use Windows Sockets API (Winsock), which is a user-mode component, to receive HTTP requests.

    Kernel & User Mode

    On widows (or most of modern OS) the program is allowed to run in kernel mode or user mode. When OS is first loaded, the windows kernel is started. It runs in kernel mode and set up paging and virtual memory.

    The CPU is actually spending time in two very distinct modes:

    • Kernel Mode: In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC.
    • User Mode: In User mode, the executing code has no ability to directly access hardware or reference memory. Code running in user mode must delegate to system APIs to access hardware or memory. Due to the protection afforded by this sort of isolation, crashes in user mode are always recoverable. Most of the code running on your computer will execute in user mode.

    In windows task manager, under performance chart, the green line is total CPU time; the red line is Kernel time. The gap between the two is User time.

    The two modes are enforced by CPU hardware, x86 CPU hardware actually provides four protection rings: 0, 1, 2, and 3. only rings 0 (Kernel) and 3 (User) are typically used.
    Most of system drivers runs in kernel mode for maximum performance and other programs runs in User mode (some drivers may run in user mode) for maximum stability. User mode is clearly a net public good, but it comes at a cost.  Transitioning between User and Kernel mode is expensive. It’s why software that throws exceptions is slow, for example. Exceptions imply kernel mode transitions. Granted, we have so much performance now that we rarely have to care about transition performance, but when you need ultimate performance, you definitely start caring about kernel mode.
    How HTTP.sys Works

    When you create a Web site, IIS registers the site with HTTP.sys, which then receives any HTTP requests for the site. HTTP.sys functions like a forwarder, sending the Web requests it receives to the request queue for the user-mode process that runs the Web site or Web application. HTTP.sys also sends responses back to the client.

    Other than retrieving a stored response from its internal cache, HTTP.sys does not process the requests that it receives. Therefore, no application-specific code is ever loaded into kernel mode. As a result, bugs in application-specific code cannot affect the kernel or lead to system failures.

    HTTP.sys provides the following services in IIS 6.0:

    • Routing HTTP requests to the correct request queue.
    • Caching of responses in kernel mode.
    • Performing all text-based logging for the WWW service.
    • Implementing Quality of Service (QoS) functionality, which includes connection limits, connection timeouts, queue-length limits, and bandwidth throttling.

    When IIS 6.0 runs in worker process isolation mode, HTTP.sys listens for requests and queues those requests in the appropriate queue. Each request queue corresponds to one application pool. An application pool corresponds to one request queue within HTTP.sys and one or more worker processes.

    When IIS 6.0 runs in IIS 5.0 isolation mode, HTTP.sys runs like it runs in worker process isolation mode, except that it routes requests to a single request queue.

    If a defective application causes the user-mode worker process to terminate unexpectedly, HTTP.sys continues to accept and queue requests, provided that the WWW service is still running, queues are still available, and space remains in the queues.

    When the WWW service identifies an unhealthy worker process, it starts a new worker process if outstanding requests are waiting to be serviced. Thus, although a temporary disruption occurs in user-mode request processing, an end user does not experience the failure because TCP/IP connections are maintained, and requests continue to be queued and processed.

    Note : A web farm is a multi-server scenario. So we may have a multiple servers for an application. If the load on one server is in excess then the other servers step in to bear the brunt.How they bear it is based on various models.
    • RoundRobin. (All servers share load equally)
    • NLB (economical)
    • HLB (expensive but can scale up to 8192 servers)
    • Hybrid (of 2 and 3).
    • CLB (Component load balancer).
    A web garden is a multi-processor setup. i.e. a single server . How to implement webfarms in .Net:
    Go to web.config and here for mode you have 4 options.
    • Say mode inproc (non web farm but fast when you have very few customers).
    • Say mode StateServer (for webfarm).
    • Outproc
     Whether to use option b or c depends on situation. StateServer is faster but SqlServer is more reliable and used for mission critical applications.

    IIS 6.0 provides four Internet services

    • WWWServices :The World Wide Web Publishing Service (WWW service) for hosting Internet and intranet content.
    • FTP Service :The File Transfer Protocol (FTP) service for hosting sites where users can upload and download files.
    • NNTP Service :The Network News Transfer Protocol (NNTP) service for hosting discussion groups.
    • SMTP Service :The Simple Mail Transfer Protocol (SMTP) service for sending and receiving e-mail messages.

    The World Wide Web Publishing Service

    The World Wide Web Publishing Service (WWW service) provides Web publishing for IIS, connecting client HTTP requests to Web sites running on an IIS-based Web server.

    The WWW service manages and configures the IIS core components that process HTTP requests. These core components include the HTTP protocol stack (HTTP.sys) and the worker processes.

    The WWW service includes these subcomponents: Active Server Pages (ASP), Internet Data Connector, Remote Administration (HTML), Remote Desktop Web Connection, server-side includes (SSI), Web Distributed Authoring and Versioning (WebDAV) publishing, and ASP.NET.
    ¦lt;br /> Worker Processes (IIS 6.0)

    A worker process is user-mode code whose role is to process requests, such as processing requests to return a static page, invoking an ISAPI extension or filter, or running a Common Gateway Interface (CGI) handler.

    In both application isolation modes, the worker process is controlled by the WWW service.  However, in worker process isolation mode, a worker process runs as an executable file named W3wp.exe

    Worker processes use HTTP.sys to receive requests and to send responses by using HTTP.  Worker processes also run application code, such as ASP.NET applications and XML Web services. You can configure IIS to run multiple worker processes that serve different application pools concurrently. This design separates applications by process boundaries and helps achieve maximum Web server reliability.

    By default, worker processes in worker process isolation mode run under the Network Service account, which has the strongest security (least access) compatible with the functionality that is required. IIS 5.0 isolation mode will be discussed later in this article.

    Inetinfo.exe (IIS 6.0)

    When IIS 6.0 runs in worker process isolation mode,Inetinfo.exe is a user-mode component that hosts the IIS metabase and that also hosts the non-Web services of IIS 6.0, including the FTP service, the SMTP service, and the NNTP service. Inetinfo.exe depends on IIS Admin service to host the metabase.

    When IIS 6.0 runs in IIS 5.0 isolation mode, Inetinfo.exe functions much as it did in IIS 5.0. In IIS 5.0 isolation mode, however, Inetinfo.exe hosts the worker process, which runs ISAPI filters, Low-isolation ISAPI extensions, and other Web applications.

    In IIS6.0, regardless of the application isolation mode used, the services that run in Inetinfo.exe run as dynamic-link libraries (DLLs) under the Local System account. Because a Local System account allows users access to every resource on the local computer.

    IIS 5.0 isolation mode

    IIS 5.0 isolation mode provides compatibility for applications that were designed to run in earlier versions of IIS. When IIS 6.0 is running in IIS 5.0 isolation mode, request processing is almost identical to the request processing in IIS 5.0. When a server is working in IIS 5.0 isolation mode, application pools, recycling, and health monitoring features are unavailable.
    Figure 2 : below shows the IIS 5.0 isolation mode.

    Note : Use IIS 5.0 isolation mode only if components or applications do not function in worker process isolation mode.

    COM makes it possible to create DLL servers that can be loaded into a surrogate EXE process. This combines the ease of writing DLL servers with the benefits of executable implementation.The dllhost.exe process goes by the name COM Surrogate ,which is an general purpose executable to host dlls out of process.If there is any unhandlled error in user dll which may crash the COM Surrogate process leaving the originating process intact.

    Application Pools

    When you run IIS 6.0 in worker process isolation mode, you can separate different Web applications and Web sites into groups known as application pools.Every application within an application pool shares the same worker process. Because each worker process operates as a separate instance of the worker process executable, W3wp.exe, the worker process that services one application pool is separated from the worker process that services another. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This ensures that if a worker process fails, it does not affect the applications running in other application pools.

    Use multiple application pools when you want to help ensure that applications and Web sites are confidential and secure.

    Note : You can’t configure two diferent version of ASP.Net (say 1.1 and 2.0) application is single application pool (same IIS process) because different versions of the .NET Framework and run time cannot coexist side by side within the same process. For this to work you need to create atleast pools each version of ASP.net application.

    ISAPI

    Internet Server Application Programming Interface (ISAPI), is an API developed to provide the application developers with a powerful way to extend the functionality of Internet Information Server (IIS). ISAPI extensions are true applications that run on IIS and have access to all of the functionality provided by IIS. As an example of how powerful ISAPI extensions can be, ASP.Net pages are processed through an ISAPI extension called aspnet_isapi.dll. ISAPI extensions are implemented as DLLs that are loaded into a process that is controlled by IIS. Like ASP and HTML pages, IIS uses the virtual location of the DLL file in the file system to map the ISAPI extension into the URL namespace that is served by IIS.Extensions and filters are the two types of applications that can be developed using ISAPI.

    Application mappings

    Application mappings (or script mappings) are the Web server equivalent of file associations in Windows.In IIS, ASP.Net functionality is contained in an ISAPI extension called aspnet_isapi.dll. Any file that is requested from the IIS server that ends in “.aspx” is mapped to aspnet_isapi.dll which is assigned to process the file before displaying its output in the client’s window.On arrival of first request on IIS , IIS loads appropriates ISAPI extenstion dll and call  ISAPI extension’s HttpExtensionProc function,the ISAPI extension carries out the actions it was designed to perform: for example, reading more data from the client (as in a POST operation), or writing headers and data back to the client.For each request, IIS perform all initialization and uninitialization from within HttpExtensionProc.

    In the next article of this series “ASP.Net Internals” we will discuss in detail how ASP.Net is related to worker process and how it gets activated when HTTP.sys recieves an request for aspx resouce on you web server (IIS).

  • Visual Studio 2008 and 2010 IDE Tips

    I didn’t get much time to write article on Vs 2008 and Vs 2010 IDE tips and tricks. I will extent the article on some day, mean while please visit links mentioned below. The article (in future) will cover how to use VS IDE from new developer point of view and will also include various tips and tricks (including various project templates – purpose) for VS 2005, VS 2008 and VS 2010 IDE.