ASP.NET HttpHandlers – Are they really required?

ASP.NET HttpHandler is a process that runs in response to a request that is made to an ASP.NET Web application. Almost everything we do in an HttpHandler, can be done in a normal .aspx page. So, why do we need HttpHandlers? Are they really required?

Given below is the explanation of why HttpHandlers are really required:
  1. Reusability & Portability – HttpHandlers are more reusable and portable than normal .aspx pages. Since there are no visual elements in an HttpHandler, they can be easily placed into their own assembly and reused from project to project.
  2. HttpHandlers are relatively less expensive than the PageHandler. A page goes through a set of events to be processed at the server (such as onInit, onLoad, etc.), ViewState and postbacks or simply the complete Page Life Cycle. When you really have nothing to do with the complete page life cycle (like displaying images), HttpHandlers are very useful.

Handlers in ASP.NET

Handler is an agent of communication or a medium which is responsible for communication in the absence of the actual user. Technically, a Handler is a class which is responsible for Instantiation of a class i.e; allocation of memory.

Console applications or Windows applications do not have handlers. We declare a class and create an object of that class in the Main() method. We as a developer are solely responsible for handling the class – specifically - instantiation of the class.

However, Web applications have handlers. In GUI Web Applications we never create an object of the “_default” page which inherits the Page class.
In Web Services, the Web Service class is never instantiated.
In WCF, the Service class, which inherits the IService Interface is never instantiated.

Now comes the question – Who instantiates the above mentioned classes?

Behind the scene, the Handler is responsible for instantiation of the above mentioned classes. ASP.NET maps HTTP requests to HTTP handlers based on the extension of the requested file (type of file). Each HTTP handler can process individual HTTP URLs or groups of URL extensions in an application. ASP.NET includes several built-in HTTP handlers:

a)    ASP.NET – System.Web.UI.PageHandlerFactory
b)    Web Service – System.Web.Services.Protocols.WebServiceHandlerFactory
c)    WCF – System.ServiceModel.Activation.ServiceHttpHandlerFactory

There are different drivers for different protocols. The driver or API of the protocol (ex – http.sys) has to have the ability to differentiate and resolve requests.
 
.sys files are the drivers for protocols. http.sys file is a driver or API or listener for the HTTP protocol. You can say that HTTP is abstraction, while http.sys is encapsulation. http.sys file handles the request and response in HTTP. The http.sys file is located in C:\Windows\System32\drivers\ folder.

When a request arrives on the server, the drivers for the protocols (.sys files) handles that request and forwards that request to a particular handler according to the extensions.

Conversion of Seconds to HH:MM:SS format

Recently I faced a requirement of converting seconds to HH:MM:SS format. After some R&D, I found the following solution:

CODE

DECLARE @in_seconds int

SET @in_seconds = 3661 -- One Hour One Minute and One Second

SELECT CONVERT(CHAR(8), DATEADD(SECOND, @in_seconds, 0), 108) As Hour_Minute_Second

OUTPUT

01:01:01

Note: This SQL code is applicable only for time less than 24 hours.

To overcome this limitation of 24 hours, I created the following function, which has the ability to return correct time duration for large time duration in seconds:

USE [AdventureWorks]
GO
/****** Object:  UserDefinedFunction [dbo].[fnc_convert_seconds_to_HHMMSS]    Script Date: 10/02/2013 08:48:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[fnc_convert_seconds_to_HHMMSS]
(
@dc_time decimal(18,2)
)

RETURNS VARCHAR(20)

AS

BEGIN
RETURN REPLACE(STR(CONVERT(INT,@dc_time/3600), LEN(LTRIM(CONVERT(INT,@dc_time/3600)))) + ':' + STR(CONVERT(INT,(@dc_time/60)%60), 2) + ':' + STR(@dc_time%60, 2), ' ', '0')
END

Example: SELECT dbo.fnc_convert_seconds_to_HHMMSS(36460) AS vc_time_in_HHMMSS

Output: 10:07:40

Enumerate the Steps for creating a Shared Assembly

Step 1: Generate a Strong Name Key:

D:\Project\DLL\sn -k dll.snk

The above statement will write a Kay pair to dll.snk file

Step 2: Associate the Strong Name Key with source code

Step 2.1: Create a program to be used as DLL - First.cs

using System;
using System.Reflection;

[assembly:AssemblyKeyFile("dll.snk")]
public class Employee
{
public string Data()
{
return "Anuj Ranjan";
}
}

a) Save the file as First.cs in D:\Project\DLL\First.cs
b) Compile the program to create a DLL from the Command Prompt as given below:

D:\Project\DLL>csc /t:library First.cs

c) The above statement will create a DLL named First.dll, with the strong name key in it.

Step 2.2: Create another program to implement the DLL - Second.cs

using System;

public class Trial
{
public static void Main()
{
Employee e = new Employee();
Console.WriteLine(e.Data());
}
}

Save the file as Second.cs in D:\Project\Implement\Second.cs

Step 3: Install the DLL in GAC

D:\Project\DLL\GACUTIL -i First.dll

GACUTIL is a command which is used to install a strong named dll in the Global Assembly Cache.

Step 4: Add the reference of the DLL in the program

D:\Project\Implement\csc /r:d:\Project\DLL\First.dll Second.cs

Step 5: Execute the program

D:\Project\Implement\Second

Fundamental Windows Communication Foundation Concepts

WCF programming model consists of a runtime and a set of APIs and is used for creating systems that communicate (sends and receives messages) between clients and services.

Messaging and Endpoints

The main concept of WCF is Message–Based Communication. In the programming model anything that can can be modeled as a message (an HTTP request, a Message Queuing – MSMQ, etc), can be represented in a uniform way. This concept enables a unified API across contrasting transport mechanisms.

A client is an application which initiates a communication, while a service is an application which responds to the client's request. However, the client and the service may not be necessarily different applications, a single application may in fact act both as a client and a service (Duplex Services and Peer–to– Peer Networking).

As Endpoints are points or spots for message exchange, they define all the information required to facilitate message exchange. A WCF service can expose single or multiple endpoints (application endpoints or infrastructure endpoints or both). The client generated endpoint should be compatible with one of the service's endpoints.

Endpoints describe the address (location of the endpoint where the messages should be send), binding (how a client can communicate with the endpoint by sending messages), contracts (form of the message) and behaviors (local implementation details of the endpoint). This information can be exposed by the service as metadata, that can be processed to generate appropriate WCF clients and communication stacks.

Communication Protocols

The two elements required in the communication stack is given below:
  • Transport protocol – Messages can be exchanged over the internet using common protocols such as HTTP and TCP. Protocols that support communication with Message Queuing applications and nodes on a Peer Networking mesh are also included.
  • Encoding mechanisms – Encoding mechanisms specify the format of a message. Following encoding mechanisms are provided by WCF:
    a) Text encoding – this is an interoperable encoding.
    b) Message Transmission Optimization Mechanism (MTOM) encoding – this is an interoperable way for efficiently sending unstructured binary data to and from a service.
    c) Binary encoding – this is implemented for efficient transfer.
Note: Even more encoding mechanisms (for example, a compression encoding) can be added using the built-in extension points of WCF.

Message Patterns

Amongst the several messaging patterns supported by WCF, the most common Message Exchange Patterns include Request–Reply, One–Way, and Duplex. The variety of interactions supported by different protocols depends on the fact that they support different Message Exchange Patterns (MEX).

The messages exchanged in WCF is secure and reliable (a feature of WCF APIs and runtime).

Conversion of Seconds to Hours:Minutes:Seconds format

Recently I faced a requirement of converting seconds to Hours:Minutes:Seconds format. After some R&D, I found the following solution:

CODE

DECLARE @in_seconds int

SET @in_seconds = 3661 -- One Hour One Minute and One Second

SELECT CONVERT(CHAR(8), DATEADD(SECOND, @in_seconds, 0), 108) As Hour_Minute_Second

OUTPUT

01:01:01

Note: This SQL code is applicable only for time less than 24 hours.