Rajnish Noonia

Category: Architecture

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

  • WPF Introduction

    The Windows Presentation Foundation (or WPF) is a graphical subsystem for rendering user interfaces in Windows-based applications. WPF, was initially released as part of .NET Framework 3.0. Designed to remove dependencies on the aging GDI subsystem, WPF is built on DirectX, which provides hardware acceleration and enables modern UI features like transparency, gradients and transforms. WPF provides a consistent programming model for building applications and provides a clear separation between the user interface and the business logic.

    WPF also offers a new markup language, known as XAML which is an alternative means for defining UI elements and relationships with other UI elements. A WPF application can be deployed on the desktop or hosted in a web browser. It also enables rich control, design, and development of the visual aspects of Windows programs. It aims to unify a number of application services: user interface, 2D and 3D drawing, fixed and adaptive documents, advanced typography, vector graphics, raster graphics, animation, data binding, audio and video.

    Microsoft Silverlight is a web-based subset of WPF that enables Flash-like web and mobile applications with the same programming model as .NET applications. 3D features are not supported, but XPS and vector-based drawing are included.

    It is compatible with multiple web browser products used on Microsoft Windows, Linux (using Novell Moonlight), Mac OS X operating systems & Mobile devices.

    WPF is designed to allow you to create dynamic, data driven presentation systems. Every part of the system is designed to create objects through property sets that drive behavior. Data binding is a fundamental part of the system, and is integrated at every layer.

    Traditional applications create a display and then bind to some data. In WPF, everything about the control, every aspect of the display, is generated by some type of data binding. The text found inside a button is displayed by creating a composed control inside of the button and binding its display to the button’s content property.

    Display technology evolution on windows …

    • User32 : Standard controls like buttons, textbox etc. This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities. Window forms are using User32 to render several controls including .net 2.0,vb, vc++ etc.
    • GDI (Graphics device interface) : Abstract graphics of drawing from hardware’s like printers ,monitors etc. Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on the hardware display. In other words it encapsulates all complexities of hardware in the GDI API. Several GDI API are available in windows platform to perform custom drawing. Hooks like subclassing cab be used to override default drawing of win32 controls on windows Or developers can create custom controls and use GDI API’s to render on screen.
    • GDI+ : JPG, PNG Image support, gradient shading, Anti Alising. GDI+ was introduced which basically extends GDI and provides extra functionalities like jpg and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support. Object oriented approach to flat GDI+ API’s are available in .net which internally based on GDI+.
    • DirectX : Targeted for game programmers, Hardware  Acceleration (is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU.),support for animation,3D support, full colour graphics, Capture and play streaming media. One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics , media streaming facility and lot more.
    • WPF : Based on direct (internally), support for primitive objects like text, shapes, controls etc, declarative UI using XAML, support for audio , video formats, define styles and templates for UI elements.  DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you can go one more step further and build animations.WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. You can also express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built over DirectX.

     The figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore.

     User32 :  It decides which goes where on the screen. User32 is used to determine what program gets what real estate. As a result, it’s still involved in WPF, but it plays no part in rendering common controls.

    • DirectX : WPF uses directX internally. DirectX talks with drivers and renders the content.
    • Milcore :  Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. The composition engine in milcore is extremely performance sensitive, and required giving up many advantages of the CLR to gain performance. Milcore.dll is the core of the WPF rendering system and the foundation of the Media Integration Layer (MIL). Its composition engine translates visual elements into the triangle and textures that Direct3D expects. Though milcore.dll is considered a part of WPF, it’s also an essential system component for Windows Vista. The Desktop Window Manager (DWM) in Windows Vista uses milcore.dll to render the desktop.
    • Presentation core :– This is a low level API exposed by WPF providing features for 2D , 3D , geometry etc.,  includes base types, such as UIElement and Visual, from which all shapes and controls derive.
    • Presentation framework :  This section has high level features like application controls , layouts . Content etc which helps you to build up your application. The vast majority of Windows Presentation Foundation developers will work exclusively with this layer.
    • *Red colour box indicate WPF layer.

     

    Silverlight : WPF on web – platform independence

    The Silverlight runtime plug-in is essentially a ‘micro’ version of the .NET CLR. This runtime is hosted�
    within the client side browser. This runtime will host your Silverlight assemblies, as well as the Silverlight base class libraries. This runtime will JIT CIL code, handle threads, exceptions and garbage collection. This is a good thing, as your current .NET programming skills apply directly to Silverlight development.

    In addition to the ‘micro-CLR’, Silverlight supports a subset of the .NET base class libraries. When a�
    requesting browser loads a Silverlight page, any required assemblies are downloaded to the user’s machine, if they are currently not installed. Like any other .NET program, you can build your own code custom libraries for use within your Silverlight programs.

    A Silverlight application is deployed from a web server as an ‘XAP’ (zip file) package. The XAP file contains the compiled Silverlight assembly, any embedded resources, and any referenced assemblies. The Silverlight runtime downloads the XAP package and executes its contents in web browser.

    Once loaded by the plug-in, the SL application is able to make remote calls (to the web server or any arbitrary endpoint) using WCF technologies. The entire web page does *not* need to be refreshed when the SL web plug in changes state. This can greatly enhance the end user experience.

    Silverlight architecture is altogether different that WPF, however it tries to implement the features available in WPF. From developer prospective there is no major difference in WPF or Silverlight even though Silverlight CLR is not same as WPF CLR.

  • Composite Application Guidance with Prism 2.0

    Composite Application Guidance, affectionately known as Prism, version 2 was released in oct 2009.  Prism provides guidance and code that can help you build modular applications that can adapt to constant changing requirements. Prism guidance is a set of tools, samples, references and written guidance to help you more easily build modular applications.  Generally the “modular” application will feature several screens, flexible user interaction and role-based behavior.  Composite applications using these patterns are meant to be loosely coupled and contain independently evolving pieces that can work together. They are “built to last” and “built for change.” This means that the application’s expected lifetime is measured in years and that it will change in response to new, unforeseen requirements. This application may start small and over time evolve into a composite client—composite applications use loosely coupled, independently evolvable pieces that work together in the overall application. Applications that do not demand these features and characteristics may not benefit from the Composite Application Guidance.

     What’s new Prism 2.0?

    • Composite Support for Silverlight: Provides guidance on modularity, UI composition, commanding, and event aggregator in Silverlight. The Reference Implementation demonstrates how to use the Prism library with Silverlight.
    • Multi-targeting: Ability to share code between Silverlight and WPF. Provide guidance in the form of patterns, documentation, and tooling on how to share code between Silverlight and WPF. The tooling has its own msi that you can download.
    • Improved UI Composition: Added View Discovery to UI Composition. View Discovery: when a region is created, the region looks for all the ViewTypes associated with the region and automatically instantiates and loads the corresponding views. This is a simple approach to create new views.
    • Hands-on-Lab for Silverlight: Provide a Hands-on-Lab for Silverlight that walks you through how to create your first application using Prism.
    • New UI: Upgraded the UI with this release which includes new Silverlight and WPF animations.

     The Prism release adapts Model-View-ViewModel (MVVM) model (refers to this as the presentation model to match what some other pattern documentation in the greater technology world uses) in the reference implementation of the Stock Trader application.

    Prism 2 is an evolution from a July 2008 release (Prism 1) that was primarily for WPF applications.  The version v2 release brings updates and those concepts to Silverlight, including an implementation of commanding in Silverlight as well as demonstration of the use of input validation using these concepts.

    Prism consists of:

    • Reusable library components, for both WPF and Silverlight.
    • All source code, Unit tests, Automated acceptance tests.
    • Hands on labs (26) that guide you through all aspects of creating a composite application.
    • Quickstarts (9) that illustrate all components of prism.
    • A completely functional reference implementation that shows you how to build a composite application.
    • A lot of documentation and guidance:
      • How to create composite applications
      • How to use the Prism libraries
      • How to use Dependency Injection in your application (Unity)
      • How to create applications that target both WPF and Sliverlight.
      • Which design patterns were used to create prism
      • How to use separated presentation patterns (like Model – View – Viewmodel) to test your UI logic
      • And much, much more.
    • Api Reference documentation
    • A Visual Studio Plugin that helps you to target both WPF and Silverlight with a single codebase. 

    You should consider using prism:

    • If you want to create modular applications, in WPF and / or Silverlight so you can Develop, Test, Version and Deploy your modules independently of each other.
    • If you want to create an application that targets both WPF and Silverlight with a single codebase, or at least reuse a lot of code assets between WPF and Sliverlight.
    • If you want to minimize initial download size Silverlight applications. Prism allows you to just download the minimum of functionality you need to start your application. Other modules can be downloaded on a background thread or on demand.
    • If you are interested in using separated presentation patterns, because you want to create Unit Tests for your UI logic or if you want to make it easier to reskin your application.

    Links :

  • Design patterns

    What are Design patterns ?

    In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.

    Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn’t require specifics tied to a particular problem.

    In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.

    To summarize, all design patterns have the following characteristics …

    • A name
    • A description of the problem being addressed
    • A description of the solution
    • An evaluation of the pattern’s consequences (i.e. its trade-offs)

    As software developers and architects, why should we care about design patterns?

    • Design patterns provide a common vocabulary, and therefore facilitate communication.
    • Design patterns provide templates or guidelines for solving common design problems.
    • Design patterns help us understand the consequences of our design decisions.

    Main categories of design patterns?

    There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

    Creational Patterns (all about creation of objects)

    • Factory Method: – Creates an instance of several derived classes.
    • Abstract Factory: – Creates an instance of several families of classes.
    • Builder: – Separates object construction from its representation.
    • Prototype: – A fully initialized instance to be copied or cloned.
    • Singleton: – A class in which only a single instance can exist.

    Structural Patterns

    • Adapter:-Match interfaces of different classes.
    • Bridge:-Separates an object’s abstraction from its implementation.
    • Composite:-A tree structure of simple and composite objects.
    • Decorator:-Add responsibilities to objects dynamically.
    • Façade:-A single class that represents an entire subsystem.
    • Flyweight:-A fine-grained instance used for efficient sharing.
    • Proxy:-An object representing another object.

    Behavioural Patterns

    • Mediator:- Defines simplified communication between classes.
    • Memento:-Capture and restore an object’s internal state.
    • Interpreter: – A way to include language elements in a program.
    • Iterator:-Sequentially access the elements of a collection.
    • Chain of Resp: – A way of passing a request between a chain of objects.
    • Command:-Encapsulate a command request as an object.
    • State:-Alter an object’s behavior when its state changes.
    • Strategy:-Encapsulates an algorithm inside a class.
    • Observer: – A way of notifying change to a number of classes.
    • Template Method:- Defer the exact steps of an algorithm to a subclass.
    • Visitor:- Defines a new operation to a class without change.

    Deep dive in design patterns?

    Final notes:

    I think patterns as a whole can help people learn object-oriented thinking: how you can leverage polymorphism, design for composition, delegation, balance responsibilities, and provide pluggable behavior. Patterns go beyond applying objects to some graphical shape example, with a shape class hierarchy and some polymorphic draw method. You really learn about polymorphism when you’ve understood the patterns. So patterns are good for learning OO and design in general.

    A lot of the patterns are about extensibility and reusability. When you really need extensibility, then patterns provide you with a way to achieve it and this is cool. But when you don’t need it, you should keep your design simple and not add unnecessary levels of indirection.

     Trying to use all the patterns is a bad thing, because you will end up with synthetic designs—speculative designs that have flexibility that no one needs. These days software is too complex. We can’t afford to speculate what else it should do. We need to really focus on what it needs. That’s why I like refactoring to patterns.