Thursday, March 25, 2010

SOA-based WCF architecture

The WCF architecture is based on the design principles of service-oriented architecture (SOA).




SOA is a framework that is used to design service-based distributed systems. In an SOA-based system, platform-independent services communicate across networked computers or computer processes.


WCF implements.
  • Explicit boundaries WCF services function using defined interfaces to identify the communications that flow outside the boundaries of the service.
  • Independent services All WCF services are deployed and managed independently; they are independent of deployment, installation, and version issues. Also, each service interaction is independent of other interactions.
  • Schema and contract-based communication WCF services communicate with clients by providing only the schema of the message and not its implementation classes. This helps developers change the service implementation in the future without impacting the clients.
  • Policy-based compatibility Compatibility between WCF services and clients at run time is determined using published policies. Policies help separate the description of the service from its implementation details.





The SOA-based WCF architecture contains four layers – Contracts, Service Runtime, Messaging, and Hosting.  


Contracts: The Contracts layer describes the WCF message system.
This is described in terms of
  • A Service Contract describes the method signatures of a service. It's defined using programming languages, such as Visual Basic and Visual C# and is distributed as an interface  
  • A Data Contract enables .NET types to be expressed in XML. The data contract describes every parameter that makes up every message that a service can create or consume.  The message parameters are defined by XML Schema definition language (XSD) documents, enabling any system that understands XML to process the documents.
  • Message Contracts define the structure of SOAP messages exchanged between a service and a client, and they allow you to view or modify messages and allows finer-grained control over parts of the message
  • Policies and Bindings : Policies and Bindings stipulate the conditions required to communicate with a service.They define the configuration, such as security levels, required by clients to communicate with a service.


Service Runtime
It describes the runtime behaviors of the service
  • Throttling controls how many messages are processed, which can be varied if the demand for the service grows to a preset limit.
  • Error behaviour decides the sequence of events when an occurs in service. This prevents the display of too much of error information to outside entities.
  • Metadata behavior governs how and whether metadata is made available to the outside world
  • Message inspection is the facility to inspect parts of a message
  • Instance behavior specifies how many instances of the service can be run (for example, a singleton specifies only one instance to process all messages).
  • Transaction behavior enables the rollback of transacted operations if a failure occurs. 
  • Dispatch behavior is the control of how a message is processed by the WCF infrastructure.
  • Parameter filtering enables preset actions to occur based on filters acting on message headers


Messaging
The Messaging layer contains channels that process messages and operate on messages and message headers.A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels operate on messages and message headers.


There are two types of channels: transport channels and protocol channels.
Transport channels read and write messages from the network, and protocol channels implement message processing protocols.Some transports use an encoder to convert messages (which are represented as XML Infosets) to and from the byte stream representation used by the network. Examples of transports are HTTP, named pipes, TCP, and MSMQ. Examples of encodings are XML and optimized binary.


Protocol channels implement message processing protocols, often by reading or writing additional headers to the message. Examples of such protocols include WS-Security and WS-Reliability.
  • WS-Security is an implementation of the WS-Security specification enabling security at the message layer.
  • The WS-Reliable Messaging channel enables the guarantee of message delivery.
  • The encoders present a variety of encodings that can be used to suit the needs of the message.
  • The HTTP channel specifies that the HyperText Transport Protocol is used for message delivery.
  • The TCP channel similarly specifies the TCP protocol.
  • The Transaction Flow channel governs transacted message patterns.
  • The Named Pipe channel enables interprocess communication.
  • The MSMQ channel enables interoperation with MSMQ applications.


Fig- A typical WCF architectural flow





Hosting and Activation
The Hosting layer describes the ways in which a WCF service can be hosted. WCF services can be hosted using either Windows Activation Services, Internet Information Services, Windows Services, .EXE, or COM+.
  •  A service is a program. Like other programs, a service must be run in an executable. This is known as a self-hosted service.
  • Services can also be hosted, or run in an executable managed by an external agent, such as IIS or Windows Activation Service (WAS). 
  • COM+ components can also be hosted as WCF services.

Windows Communication Foundation (WCF) - Glossary

WCF Fundamentals
  • Service are applications that wait for clients to communicate with them and respond to that communication. They expose the functionalities to client.
  • Client initiate the communication. They consume the service offered by Service.
  • Message: A message is a self-contained unit of data that may consist of seveal parts, including a body and headers. Clients & Service  communicate using XML messages.


A single application can act as both a client and a service.


Endpoints
Messages are sent between endpoints. Endpoints are places where messages are sent or received (or both), and they define all the information required for the message exchange. A service exposes one or more application endpoints (as well as zero or more infrastructure endpoints), and the client generates an endpoint that is compatible with one of the service's endpoints.


An endpoint describes in a standard-based way where messages should be sent, how they should be sent, and what the messages should look like. A service can expose this information as metadata that clients can process to generate appropriate WCF clients and communication stacks.









An endpoint consists of these components:
  • address Each endpoint has a unique address that helps a client know where it is located on the network.It is specified as a Uniform Resource Identifier (URI). The URI schema part names the transport mechanism to use to reach the address, such as HTTP and TCP. The hierarchical part of the URI contains a unique location whose format is dependent on the transport mechanism.  The client uses this address to send messages to an endpoint. An address can be absolute or relative. If you enter a relative address, WCF uses the absolute base address as the prefix for it. An example of an absolute address is http://localhost:8888/SampleService.
  • binding The binding of an endpoint describes the channels used to communicate with the endpoint. A channel is a route through which all messages pass in a WCF architecture. A channel is composed of binding elements that tell clients which transport protocol, encoding, and security configurations should be used to communicate with the endpoint. WCF provides many default bindings such as BasicHttpBinding and NetTcpBinding.
  • contract An endpoint's contract informs clients about the type of capabilities or features the endpoint provides. It tells clients the form of the message, what operations they can call, how they can call an operation, and what response message they will receive from the endpoint. A contract is created by applying the  ServiceContract attribute to an interface or class description and applying the OperationContract attribute to each method included as a service operation.


An WCF service is exposed to the world as a collection of endpoints.
  • Infrastructure endpoint An endpoint that is exposed by the infrastructure to facilitate functionality that is needed or provided by the service that does not relate to a service contract. For example, a service might have an infrastructure endpoint that provides metadata information.
  • Application endpoint An endpoint exposed by the application and that corresponds to a service contract implemented by the application.
  • Binding element A binding element represents a particular piece of the binding, such as a transport, an encoding, an implementation of an infrastructure-level protocol (such as WS-ReliableMessaging), or any other component of the communication stack.
  • service operation: A service operation is a procedure defined in a service's code that implements the functionality for an operation. This operation is exposed to clients as methods on a WCF client. The method may return a value, and may take an optional number of arguments, or take no arguments, and return no response. For example, an operation that functions as a simple "Hello" can be used as a notification of a client's presence and to begin a series of operations.
  • service contract :The service contract ties together multiple related operations into a single functional unit. The contract can define service-level settings, such as the namespace of the service, a corresponding callback contract, and other such settings. In most cases, the contract is defined by creating an interface in the programming language of your choice
  • Operation contract: An operation contract defines the parameters and return type of an operation. When creating an interface that defines the service contract, you signify an operation contract by applying the OperationContractAttribute attribute to each method
  • Message contract:A message contract describes the format of a message. For example, it declares whether message elements should go in headers versus the body, what level of security should be applied to what elements of the message, and so on.
  • Fault contract: A fault contract can be associated with a service operation to denote errors that can be returned to the caller. An operation can have zero or more faults associated with it. These errors are SOAP faults that are modeled as exceptions in the programming model.
  • Data contract: The data types a service uses must be described in metadata to enable others to interoperate with the service. The descriptions of the data types are known as the data contract, and the types can be used in any part of a message, for example, as parameters or return types. If the service is using only simple types, there is no need to explicitly use data contracts.


Behaviors
  • A behavior is a component that controls various run-time aspects of a service, an endpoint, a particular operation, or a client.
  • Behaviors are grouped according to scope.
  • Common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations. For example, one service behavior is throttling, which specifies how a service reacts when an excess of messages threaten to overwhelm its handling capabilities. An endpoint behavior, on the other hand, controls only aspects relevant to endpoints, such as how and where to find a security credential.
Communication Protocols
One required element of the communication stack is the transport protocol. Messages can be sent over intranets and the Internet using common transports, such as HTTP and TCP. Other transports are included that support communication with Microsoft Message Queuing (MSMQ) applications and nodes on a Peer Networking mesh. More transport mechanisms can be added using the built-in extension points of WCF.


Encoding is specified in communication stack which specifies how any given message is formatted. WCF provides the following encodings:
  • Text encoding, an interoperable encoding.
  • Message Transmission Optimization Mechanism (MTOM) encoding, which is an interoperable way for efficiently sending unstructured binary data to and from a service.
  • Binary encoding for efficient transfer.
More encoding mechanisms (for example, a compression encoding) can be added using the built-in extension points of WCF.


Message Patterns
The message exchange patterns used in WCF are either
  • One Way: The One Way is when the sender sends a message to the receiver but the sender doesn't expect the receiver to reply to this message, it is something like Fire & Forget.
  • Request/Reply: The Request / Reply is when the sender sends a message to the receiver and expects ONLY one reply from the receiver, as an example any web page you request for it in your browser you expect a reply (Response) which is the Page you requested.
  • Duplex: The Duplex is when both Sender & Receiver construct a channel between them and everyone of them can send messages to the other at well, it is just like a Phone Call.







Hosting: A service must be hosted in some process. A host is an application that controls the lifetime of the service. Services can be self-hosted or managed by an existing hosting process.


Self-hosted service: A self-hosted service is one that runs within a process application that the developer created. The developer controls its lifetime, sets the properties of the service, opens the service, and closes the service.


metadata
  • The metadata of a service describes the characteristics of the service that an external entity needs to understand to communicate with the service. Metadata can be consumed by the ServiceModel Metadata Utility Tool (Svcutil.exe) to generate a WCF client and accompanying configuration that a client application can use to interact with the service.
  • The metadata exposed by the service includes XML schema documents, which define the data contract of the service, and WSDL documents, which describe the methods of the service.
  • When enabled, metadata for the service is automatically generated by WCF by inspecting the service and its endpoints. To publish metadata from a service, you must explicitly enable the metadata behavior.


WS-* Shorthand for the growing set of Web Service (WS) specifications, such as WS-Security, WS-ReliableMessaging, and so on, that are implemented in WCF.

Wednesday, March 24, 2010

Windows Communication Foundation - overview

WCF is a framework ( yep another framework :D ). It is a unified programming model for building service oriented applications
 
The WCF architecture uses message-based communication. This involves messages being sent between endpoints generated by either a service or a client.


A service is an application that responds to a request, and a client is an application that initiates a request. In many cases, a single application can act as both a client and a service, depending on the situation.





WCF is implemented primarily as a set of classes on top of the .NET Framework’s Common Language Runtime (CLR). Because it extends their familiar environment, WCF allows .NET developers to build service-oriented applications in a familiar way.


The benefits of WCF
  • asynchronous one-way messaging Many applications use asynchronous one-way messaging. For example, web browsers send requests to web servers and wait for replies. WCF supports asynchronous one-way messaging, which provides advanced functionality, reliability, and application responsiveness. It also makes efficient use of available processing power. Asynchronous messaging is the most efficient way of performing the input and output tasks required by a distributed application.
  • Support for cross-vendor interoperability, including  security, and transactions.  WCF has interoperability features that were previously spread across different technologies. It communicates using SOAP-based web services (WS-*) and supports Representational State Transfer (REST) architectures, Plan Old XML (POX) messaging systems, and JavaScript Object Notation (JSON) data during WCF runtimes. In addition, you can write custom extensions that enable WCF applications to communicate with applications that require proprietary message encodings.
    WCF allows transactional scopes to flow across multiple applications
    Because WCF adheres to the WS-Security specifications, its default security options range from message-based security to the more traditional transport-centric security model.
  • reliability:WCF provides four assurances for reliability for distributed computing – at most once, at least once, exactly once, and in order. An assurance is similar to a guarantee. It contains mechanisms that provide these assurances with little or no modification to the application. As opposed to traditional types of assurances, WCF's assurance mechanisms don't depend on the transport method used.  
  • platform consolidation
WCF unifies the following distributed communication technologies


ASP.NET Web Services (ASMX) and the Web Service Enhancements (WSE): The ASMX and WSE technologies provide an interoperable, service-oriented infrastructure and programming model that can easily be integrated into web services or web service clients. They work on HTTP only and can have performance issues but are interoperable because their data is encoded using XML.
Enterprise Services: Enterprise Services is a component-oriented technology that provides transaction integration across multiple objects performing related work in a distributed environment. It minimizes throttling, optimizes pooling of object instances, provides a publish/subscribe mechanism for events, and uses a fast, secure, and platform-integrated transport method. However, Enterprise Services provides poor interoperability, because it is tightly coupled with the infrastructure.
Microsoft Message Queue (MSMQ): MSMQ is a set of objects that provide a durable, volatile, and scalable message queuing system that ensures reliable data transport from one place to the next. It is used to collect a group of messages, send them to a server for processing, and receive a reply from the server. However, MSMQ cannot process corrupted messages efficiently. When a corrupted message is received by the server, it blocks other messages in the queue.
Remoting: Remoting is the application programming interface (API) used by .NET to allow .NET Framework applications to communicate across application domain boundaries. It is a very flexible and extensible model that enables developers to manipulate proxy mechanisms, transports, and the way communication channels function. However, Remoting does not provide interoperability with non-.NET applications.  


  • Explicit support for service-oriented development.
explicit boundaries WCF services function using defined interfaces to identify the communications that flow outside the boundaries of the service.
independent services All WCF services are deployed and managed independently; they are independent of deployment, installation, and version issues. Also, each service interaction is independent of other interactions.
schema and contract-based communication WCF services communicate with clients by providing only the schema of the message and not its implementation classes. This helps developers change the service implementation in the future without impacting the clients.
policy-based compatibility Compatibility between WCF services and clients at run time is determined using published policies. Policies help separate the description of the service from its implementation details.


The SOA-based WCF architecture contains four layers – Contracts, Service Runtime, Messaging, and Hosting.  


Contracts: The Contracts layer describes the WCF message system.
They are of two types- Data & Service
  • A Service Contract describes the method signatures of a service. It's defined using programming languages, such as Visual Basic and Visual C#.  
  • A Data Contract enables .NET types to be expressed in XML.
  • Message Contracts define the structure of SOAP messages exchanged between a service and a client, and they allow you to view or modify messages.  
  • Policies and Bindings
  • Policies and Bindings define the configuration, such as security levels, required by clients to communicate with a service.


A practical experience
Last year i was associated with a project (.Net 2.0) which had both Java & .net modules interacting with each other. More over there were custom adapters/interfaces (in C#) for around 500 external devices which interected with our application. Few devices provided the data for our application and few others were dependant on the data generated by our application. A specific set of meesages were send  to MSMQ for other devices to read. It was a distirbution nightmare. We had web services. custom adapters, MSMQ, remoting almost all the distributed technologies supported by Microsoft in one project. Initially we had a very difficult time managing all these.


We migrated the project to .Net 3.5. To solve this distribution nightmare we adopted WCF. The following factors helped us to choose WCF
  • Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.(We can also configure and extend WCF to communicate with Web services using messages not based on SOAP, for example, simple XML formats like RSS)
  • Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise Services are now provided by WCF. They are available to any WCF-based application, which means that the our application can use them with any of the other applications it communicates with.
  • The WCF option for queued messaging, built on Message Queuing, allows applications to use persistent queuing without using another set of application programming interfaces.
  • Performance is of paramount concern for most businesses. WCF is developed with the goal of being one of the fastest distributed application platform developed by Microsoft. (To allow optimal performance when both parties in a communication are built on WCF, the wire encoding can be used, in this case is an optimized binary version of an XML Information Set. Messages still conform to the data structure of a SOAP message, but their encoding uses a binary representation of that data structure rather than the standard angle-brackets-and-text format of the XML 1.0 text encoding.)

Wednesday, March 3, 2010

Asp.Net – Creating a new custom HTTP Module

An HTTP Module is a .NET class that executes with each and every page request. You can use an HTTP Module to handle any of the HttpApplication events that you can handle in the Global.asax file.

You are already familiar with some of the HTTP Modules like
  • FormsAuthenticationModule handles the Forms authentication
  • WindowsAuthenticationModule handles the Windows authentication
  • SessionStateModule manages the session state of ASP.net application
  • OutputCacheModule deals with output caching
  • ProfileModule used for interaction with user profiles

Each HTTP Module subscribes to one or more HttpApplication events. For example, when the HttpApplication object raises its AuthenticateRequest event, the FormsAuthenticationModule executes its code to authenticate the current user.

Below I have included a sample class which implements the IHttpModule interface

In the Init event I have created an EventHandler for the PostAuthorizeRequest event of Http Application

namespace AspNet
{
    public class CustomContentModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
         
            app.PostAuthorizeRequest += new EventHandler(SendRequest);
        }
        public void SendRequest(Object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            app.Response.Write("Hi content from HTTP Module
Pay my tax also !!!"
);
        }

        public void Dispose() { }
    }
}



You can use any of the following events of HTTP Application; the events are raised in the following order:

  1. BeginRequest
  2. AuthenticateRequest
  3. PostAuthenticateRequest
  4. AuthorizeRequest
  5. PostAuthorizeRequest
  6. ResolveRequestCache
  7. PostResolveRequestCache

      After the PostResolveRequestCache event and before the PostMapRequestHandler event, an event handler (which is a page that corresponds to the request URL) is created. When a server is running IIS 7.0 in Integrated mode and at least the .NET Framework version 3.0, the MapRequestHandler event is raised. When a server is running IIS 7.0 in Classic mode or an earlier version of IIS, this event cannot be handled.

  1. PostMapRequestHandler
  2. AcquireRequestState
  3. PostAcquireRequestState
  4.  PreRequestHandlerExecute

      The event handler is executed.

  1. PostRequestHandlerExecute
  2. ReleaseRequestState
  3. PostReleaseRequestState

      After the PostReleaseRequestState event is raised, any existing response filters will filter the output.

  1. UpdateRequestCache
  2. PostUpdateRequestCache
  3. LogRequest.

      This event is supported in IIS 7.0 Integrated mode and at least the .NET Framework 3.0
 
  1. PostLogRequest

      This event is supported IIS 7.0 Integrated mode and at least the .NET Framework 3.0
  1. EndRequest


After creating this class add the following entry in Web.config

            <httpModules>
                        <add name="CustomContentModule" type="AspNet.CustomContentModule"/>
            httpModules>

When you excute any page in this application HTTP Runtime will add the content from the HTTP module created by us. You can build on this to create more complex scenarious like custom authitication, generation.processing of data based on the paraametr availalle in the Http Application objects etc.

Tuesday, March 2, 2010

ASP.net - implementing Asynchronous HTTP handler

Asynchronous programming has its own benefits. It helps in better usage of resources. In ASP.net when a user request for a resource which is to be processed by HTTP Handler a thread is created an allocated to the handler file. The thread will be idle till the file finish it’s processing. So as to minimize this “idle” period using asynchronous programming we can release the thread back to pool after passing the execution to handler file. When the asynchronous handler completes its work, the framework reassigns a thread to the original request and the handler can render content to the browser. For a better understanding of Asynchronous programming in .Net visit: Asynchronous Programming Overview

We can create an asynchronous HTTP handler by implementing the IHttpAsyncHandler interface, which is derived from the IHttpHandler interface. It adds two additional
methods:

  • IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);—Called to start the asynchronous task.
  • void EndProcessRequest(IAsyncResult result)—Called when the asynchronous task completes

Create a new class like the following


    public class NewClass : IHttpAsyncHandler
    {
        private HttpContext _context;
        private WebRequest _request;

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
        }

        public void EndProcessRequest(IAsyncResult result)
        {
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            throw new Exception("The ProcessRequest method is not implemented.");
        }
    }

You can use this class to do a variety of tasks.

In the below Code I have used created a clss to read RSS data from web

public class RSSHandler : IHttpAsyncHandler
    {
        private HttpContext _context;
        private WebRequest _request;
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            // Store context

            _context = context;
            // Initiate call to RSS feed
           
            _request = WebRequest.Create(context.Request.QueryString["rssURL"]);
            return _request.BeginGetResponse(cb, extraData);
        }
        public void EndProcessRequest(IAsyncResult result)
        {
            // Get the RSS feed
            string rss = String.Empty;
            WebResponse response = _request.EndGetResponse(result);
            using (response)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                rss = reader.ReadToEnd();
            }
            _context.Response.Write(rss);
        }
        public bool IsReusable
        {
            get { return true; }
        }
        public void ProcessRequest(HttpContext context)
        {
            throw new Exception("The ProcessRequest method is not implemented.");
        }


This class will read the RSS feed asynchronously.

The BeginProcessRequest() method uses the WebRequest class to request the page that
contains the RSS headlines. It received the URL as QueryString.The WebRequest.BeginGetResponse() method is used to retrieve the remote page asynchronously. When the BeginGetResponse() method completes, the handler’s EndProcessRequest() method is called. This method retrieves the page and renders the contents of the page to the browser.

Before we start using this handler we have to register this handler like the following in web.config

<httpHandlers>
      <add verb="*" path="*.rss" validate="false" type="AspNet.RSSHandler"/>
                  <add verb="*" path="*.xml" validate="false" type="AspNet.RSSHandler"/>
 httpHandlers>

After building and typing the following URL

I got an output similar to the one shown below
There was no file xyz.rss or sample.xml but since these extensions were mapped to the recently created HTTP handler output was generated by the framework




Related Articles :

  1. ASP.net - Http handlers - implementing IHttpHandler
  2. ASP.net - Http handlers - Generic Hander 

Monday, March 1, 2010

ASP.net - Http handlers - implementing IHttpHandler



Implementing a generic HTTP handler has its own limitations. To give more power to handle request in any URL we can create our own HTTP handlers using the interface IHttpHandler. This interface defines the contract that ASP.NET implements to synchronously process HTTP Web requests using custom HTTP handlers.

You can create HTTP handler in any of the .net language which can run in the framework (any CLS compliant language).
In the following example I have used C#

public class ImageHandlerNew :IHttpHandler
    {
        const string connectionStringName = "Images";

        public void ProcessRequest(HttpContext context)
        {
           

        }

        public bool IsReusable
        {
            get { return true; }
        }

    }

In this example the most important function is ProcessRequest which handles the incoming request from browser, process it and sends back the response. This function takes the current running context as parameter. This context enables has all the runtime objects & context information of ASPX execution thread.
As mentioned in http://thetechjungle.blogspot.com/2010/02/aspnet-http-handlers-generic-hander.html , The IsReusable property indicates whether the same handler can be reused over multiple requests. 

You can add a lot of different functionalities like generating the PDF, excel files or retrieving the stock quotes in ProcessRequest function (when client requests for a specific resource). For testing you can use the following function which retrieves the image file stored in SQL server database.

  public void ProcessRequest(HttpContext context)
        {
            context.Response.Buffer = false;

            string filename = VirtualPathUtility.GetFileName(context.Request.Path);

            string connstring = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

            SqlConnection con = new SqlConnection(connstring);
            SqlCommand cmd = new SqlCommand("SELECT Image FROM Images WHERE FileName=@FileName", con);
            cmd.Parameters.AddWithValue("@FileName", filename);

            using (con)
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                if (reader.Read())
                {
                    int bufferSize = 8040;
                    byte[] chunk = new byte[bufferSize];
                    long retcount;
                    long startindex = 0;
                    retcount = reader.GetBytes(0, startindex, chunk, 0, bufferSize);
                    while (retcount == bufferSize)
                    {
                        context.Response.BinaryWrite(chunk);

                        startindex += bufferSize;
                        retcount = reader.GetBytes(0, startindex, chunk, 0, bufferSize);
                    }

                    byte[] actualchunk = new byte[retcount - 1];
                    Buffer.BlockCopy(chunk, 0, actualchunk, 0,(int) retcount-1);
                    context.Response.BinaryWrite(actualchunk);
                }
            }

        }

After adding thie CS file in your application add the following in web.config

<httpHandlers>
              <add verb="*" path="*.gif" validate="false" type="AspNet.ImageHandlerNew"/>
              <add verb="*" path="*.jpg" validate="false" type="AspNet.ImageHandlerNew"/>
              <add verb="*" path="*.jpeg" validate="false" type="AspNet.ImageHandlerNew"/>
      httpHandlers>

  • path: Enables you to specify the path associated with the handler. You can use wildcards in the path expression.
  • verb:Enables you to specify the HTTP verbs, such as GET or POST, associated with the handler. You can specify multiple verbs in a comma-separated list. You can represent any verb with the * wildcard.
  • type : Enables you to specify the name of the class that implements the handler.
  • validate:Enables you to specify whether the handler is loaded during application startup. When true, the handler is loaded at startup. When false, the handler is not loaded until a request associated with the handler is made. This second option can improve your application’s performance.

How to execute this Handler?
Remember once you create this handler all the requests for .gif,.jpg & .jpeg resources will be handled by this. So if the corresponding data is not available in database this code will not display anything. You don’t have to add any special code in your aspx or associated class files, ASPNET/IIS runtime will automatically redirect the corresponding resource request to this class/dll.


Using this you can create your own extensions & produce the output !!!!