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:


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



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]
/****** Object:  UserDefinedFunction [dbo].[fnc_convert_seconds_to_HHMMSS]    Script Date: 10/02/2013 08:48:33 ******/

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



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')

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;

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();

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


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:


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



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

Message Patterns in WCF Services

Client applications and WCF services communicate by passing XML messages. Message Exchange Patterns illustrate how clients and services communicate by passing messages. There are three message exchange patterns supported by WCF:

·         Request – Reply Message Exchange Pattern
·         One – Way Message Exchange Pattern (also called Datagram)
·         Duplex Message Exchange Pattern (also called Callback)

Request – Reply Message Exchange Pattern

After sending message to a WCF service, a client application waits for the reply in Request – Reply pattern. This is the default and classic pattern for both WCF and Web Services. Since the client has asked a question, and it expects an answer, it waits for the service to send a message back containing the answer.

The Request – Reply message exchange pattern is used when a client requests a service to perform an action, and it needs some confirmation. Fault exception is handled in Request – Reply pattern. The Request – Reply pattern is the most used message exchange pattern.

In Request – Reply Message Exchange Pattern, only the client can initiate a communication with the service.

One – Way Message Exchange Pattern

The One – Way Message Exchange Pattern is also known as Datagram or Fire and Forget. This pattern is used when a client requests the service to take an action but it does not need any confirmation. Thus neither the service sends a reply message not the client waits for a reply. A client sends a message (request) to a WCF service but the service does not send a reply message to the client. The client does not wait for the reply and proceeds with other processing work. Some scenario’s for one-way pattern includes logging in and out, maintenance tasks, heads down data entry and other repetitive tasks etc.

An implication of using one – way pattern is that even if a method call fails due to an exception or invalid data, the service does not notify the client. If the client needs to be notified about the failure of the service request, then this pattern should not be used. This pattern should be used when the client does not need to wait for a reply from the WCF service.

In One – Way Message Exchange Pattern, only the client can initiate a communication with the service.

Duplex Message Exchange Pattern

The Duplex Message Exchange Pattern is also known as Callback. Both the client and the service can initiate a communication in the duplex pattern. It can be used for transactions. The client calls the service, which after processing the request, callbacks the client with the reply. In the meanwhile, instead for waiting for the reply (as in Request – Reply pattern), the client proceeds with other tasks.

This pattern should be used when the client (after the client has called the service) expects a notification or alert from the WCF service.

Note: The One – Way and Duplex patterns provides opportunities to fine-tune the performance of applications and to add more flexibility regarding what happens after a client calls a service.

The presence of One – Way and Duplex patterns in WCF is a major advantage of WCF over Web Services.

Polymorphism in C#

Polymorphism is the ability of an object oriented language (C# in this context) to allow a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendents. A class’s polymorphic interface is constructed using any number of virtual or abstract members.

A virtual member is a member in a base class that defines a default implementation that may be changed (overridden) by a derived class.

In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type.

In either case (virtual or abstract), when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.

Method Overriding – Method Overriding is a process in which a derived class can define its own version of a method, which was originally defined by its base class.

Virtual Keyword – The virtual keyword indicates that the base class wants to define a method which may be (but does not have to be) overridden by a derived class. A virtual method provides a default implementation that all derived types automatically inherit. If a child class so chooses, it may override the method but does not have to.

Note: Subclasses are never required to override virtual methods.

Override Keyword – The override keyword is used by a derived class to to change the implementation details of a virtual method (defined in the base class). Each overridden method is free to leverage the default behavior of the parent class using the base keyword.

Sealed Keyword – The sealed keyword is basically applied to classes to prevent other types from extending its behavior via inheritance.

It can also be applied to virtual methods to prevent derived types from overriding those methods. Ex.

public override sealed void GiveBonus(float amount)

Any effort to override the above sealed method in the derived class will generate compile time error.

Abstract Classes – The abstract keyword can be used in the class definition to prevent direct creation of an instance of the class. Although abstract classes cannot be created directly, it is still assembled in memory when derived classes are created. Thus, it is perfectly fine for abstract classes to define any number of constructors that are called indirectly when derived classes are allocated.

An abstract class can define any number of abstract members (members that does not supply a default implementation, but must be accounted for by each derived class).

The polymorphic interface of an abstract base class simply refers to its set of virtual and abstract methods. Methods marked with abstract are pure protocol. They simply define the name, return type (if any), and parameter set (if required).

If you do not override an abstract method (of the base abstract class) in the derived class, the derived class will also be considered abstract, and would have to be marked abstract with the abstract keyword.

Although it is not possible to directly create an instance of an abstract base class, you can freely store references to any subclass with an abstract base variable.

Q: What is an efficient way to force each child class to override a virtual method?

A: To force each child class to override a virtual method, we can better define an abstract method (which by definition means you provide no default implementation whatsoever), in an abstract class.

Inheritance in C#

Inheritance is the ability of an object oriented language (C# in this context) to build new class definitions based on existing class definitions. Inheritance allows us to extend the behavior of a base (parent) class by inheriting core functionality into the derived subclass (child class). Inheritance promotes code re-usability.

Inheritance preserves encapsulation – private members of the base class can never be accessed from an object reference of the derived class. Private members can only be accessed by the class that defines it.

C# does not support Multiple Inheritance. A class in C# cannot directly derive from two or more base classes.

What is Black Box programming?

A well-encapsulated class should protect its data and hide the details of how it operates from the outside world. This is often termed Black Box programming.

The beauty of this approach is that an object is free to change how a given method is implemented under the hood. It does this without breaking any existing code making use of it, provided that the parameters and return values of the method remain constant.

The notion of Black Box programming is very closely related to the concept of Encapsulation.

Encapsulation in C#

Encapsulation is the ability of an object oriented language (C# in this context) to hide unnecessary implementation details from the object user. Encapsulation makes coding simpler and helps to preserve data integrity.

According to the concept of encapsulation, an object’s internal data should not be directly accessible from an object instance. Members of a class that represent an object’s state should not be marked as public. The state of an object should only be altered indirectly by using public members. C# prefers properties to encapsulate data. Ex.

class ABC
// private data members
private int roll;
private int class;
private string name;

// public properties
public int Roll
get { return roll; }
set { roll = value; }
public int Class
get { return class; }
set { class = value; }
public string Name
get { return name; }
set { name = value; }

// constructor
public ABC()
// values are assigned to data members via properties
Roll = 10;
Class = 9;
Name = “Rajveer Raj Banti”;

Evolution of C# (1.0 – 5.0)

C# is a multi-paradigm (structured, imperative, object-oriented, event-driven, functional, generic, reflective, concurrent) programming language. It was developed within Microsoft. The development team which consisted of Scott Wiltamuth, Peter Golde and others was led by Anders Hejlsberg.

The first version of C# was released by Microsoft in July 2000. The latest version of C# is 5.0, which was released on August 15, 2012.

C# 1.0

C# 1.0 was released by Microsoft with Visual Studio 2002. C# 1.0 targets .NET Framework 1.0. It was the first language adopted by developers to build .NET applications.

C# 1.2

C# 1.2 was released by Microsoft with Visual Studio 2003. C# 1.2 targets .NET Framework 1.1.

C# 2.0

C# 2.0 was released by Microsoft with Visual Studio 2005. C# 2.0 targets .NET Framework 2.0.
The new features added in C# 2.0 are as given below:
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Covariance and Contravariance
C# 3.0

C# 3.0 was released by Microsoft with Visual Studio 2008. It is also compatible with Visual Studio 2010. C# 3.0 targets the .NET Framework 2.0 (Except LINQ/Query Extensions), .NET Framework 3.0 (Except LINQ/Query Extensions) and .NET Framework 3.5.
The new features added in C# 3.0 are as given below:
  • Implicitly typed local variables (var)
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
  • LINQ
C# 4.0

C# 4.0 was released by Microsoft with Visual Studio 2010. C# 4.0 targets .NET Framework 4.0.
The new features added in C# 4.0 are as given below:
  • Dynamic binding (Late binding)
  • Named and optional arguments
  • Generic Covariance and Contravariance
  • Embedded interop types ("NoPIA")
C# 5.0

C# 5.0 was released by Microsoft with Visual Studio 2012. C# 5.0 targets .NET Framework 4.5.
The new features added in C# 4.0 are as given below:
  • Asynchronous methods
  • Caller info attributes

The upcoming versions of C# might include the following features:
  • Compiler-as-a-service ("Roslyn")
The Evolution of C# programming language

Casting and Reference Conversions – Differentiate between Upcasting and Downcasting

An object reference can be:
  • Implicitly upcast to a base class reference
  • Explicitly downcast to a subclass reference
Upcasting and downcasting between compatible reference types performs reference conversions: a new reference is (logically) created that points to the same object. 
An upcast always succeeds; a downcast succeeds only if the object is suitably typed.


An upcast operation creates a base class reference from a subclass reference. For example:

Vechicle oVechicle = new Vechicle();
Car oCar = oVechicle; // Upcast

After the upcast, variable oCar still references the same Vechicle object as variable oVechicle. The object being referenced is not itself altered or converted:

Console.WriteLine (oCar == oVechicle); // True

Although oCar and oVechicle refer to the identical object, oCar has a more restrictive view on that object:

Console.WriteLine (oCar.Name); // OK
Console.WriteLine (oCar.VechicleCount); // Error: VechicleCount undefined

The last line generates a compile-time error because the variable oCar is of type Car, even though it refers to an object of type Vechicle. To get to its VechicleCount field, you must downcast the Vechicle to a Car.


A downcast operation creates a subclass reference from a base class reference. For example:

Vechicle oVechicle = new Vechicle();
Car oCar = oVechicle; // Upcast

Vechicle oVechicle1 = (Vechicle)oCar; // Downcast
Console.WriteLine (oVechicle1.VechicleCount); // <No error>
Console.WriteLine (oVechicle1 == oCar); // True
Console.WriteLine (oVechicle1 == oVechicle); // True

As with an upcast, only references are affected—not the underlying object. A downcast requires an explicit cast because it can potentially fail at runtime:

Maruti oMaruti = new Maruti();
Car oCar = oMaruti; // Upcast always succeeds
Vechicle oVechicle = (Vechicle)oCar; // Downcast fails: oCar is not a Car

If a downcast fails, an InvalidCastException is thrown. This is an example of runtime type checking.

Explain the IEnumerable Interface

Namespace – System.Collections
Assembly mscorlib (in mscorlib.dll)

IEnumerable Interface is the base interface for all non-generic collections that can be enumerated. It exposes an enumerator, which supports a simple iteration over a non-generic collection. System.Collections.Generic.IEnumerable<T> is the generic version of this interface.

IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator which provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.

Implementation of IEnumerable and IEnumerator on collection classes enables the foreach syntax on a collection. The members of these interfaces are not explicitly called, but they are implemented to support the use of foreach to iterate through the collection.

Static Constructors - What is the output of the C# code?

class A
  public A(string text)

class B
  static A a1 = new A("a1");

  A a2 = new A("a2");

  static B()
    a1 = new A("a3");

  public B()
    a2 = new A("a4");

class Program
  static void Main(string[] args)
    B b = new B();


Before any code of the type B gets executed, its static constructor will be invoked first. It initializes static data fields and then executes statements inside the static constructor. Therefore, it prints a line of “a1”, and then another line of “a3”.

When the execution flow reaches the statement B b = new B(), the ordinary constructor is invoked. It initializes its data fields first and then the statements in its constructor method, so it prints a line of “a2”, and then another line of “a4”.



Access Modifiers in C#

Access Modifiers are used to control the visibility of a type (classes, interfaces, structures, enumerations, and delegates) or their members (properties, methods, constructors, and fields) to other parts of an application.

Role of each access modifier and where it may be applied:

Access Modifier Applicable to Description
public Types or type members Public items have no access restrictions. A public member can be accessed from an object, as well as any derived class. It can also be accessed from other external assemblies.
private Type members or nested types Private items can only be accessed by the class (or structure) that defines the item.
protected Type members or nested types Protected items can be used by the class which defines it, and any child class. However, protected items cannot be accessed from the outside world using the C# dot operator.
internal Type or type members Internal items are accessible only within the current assembly. Therefore, if you define a set of internal types within a .NET class library, other assemblies are not able to make use of them.
protected internal Type members or nested types
When the protected and internal keywords are combined on an item, the item is accessible within the defining assembly, the defining class, and by derived classes.

Note: By default, type members (ex. members of a class) are implicitly private while types (ex. classes) are implicitly internal.

// An internal class with a private default constructor.
class Country
// default constructor – implicitly private

Note: Nested types can have private access, but non-nested types cannot be marked private.

public class Country
// OK! Nested types can be marked private.
private enum FlagColor
Red, Green, Blue

Here, it is permissible to apply the private access modifier on the nested type. However, non-nested types (such as the Country) can only be defined with the public or internal modifiers.

// Error! Nonnested types cannot be marked private!
private class Country