Documente Academic
Documente Profesional
Documente Cultură
CLI - Common Language Infrastructure. Microsoft has a piece of shared source, its the public
implementation of ECMA Common Language Infrastructure. This shared code is code-
named "Rotor". It has around 3 million lines of code. Those who are interesed in
development of a language that targets the .NET Framework, may extensively make use of
this CLI.
CIL- Stands for Common Intermediate Language. Its actually a low level human readable
language implementation of CLI. All .NET-aware languages compile the source oode to an
intermediate language called Common Intermediate Language using the language specific
compiler. It is also possible to build .NET assemblies direclty using CIL using the ilasm.exe
compiler. This compiler is shipped along with the .NET Framework 2.0 SDK. CIL is the only
language that allows access to each aspect of the CTS. CIL is the definition of the
fundamentals of the .NET framework.
CTS - stands for Common Type Specification. It is at the core of .NET Framework's cross-
language integration, type safety, and high-performance code execution. It defines a common
set of types that can be used with many different language syntaxes. Each language (C#,
VB.NET, Managed C++, and so on) is free to define any syntax it wishes, but if that language
is built on the CLR, it will use at least some of the types defined by the CTS.
Metadata - is code that describes the compiled IL. A .NET language compiler will generate
the metadata and store this in the assembly containing the CIL. Metadata describes all class
members and classes that are defined in the assembly, and the classes and class members that
the current assembly will call from another assembly. When the CLR executes CIL it will
check to make sure that the metadata of the called method is the same as the metadata that is
stored in the calling method. This ensures that a method can only be called with exactly the
correct number of parameters and exactly the correct parameter types.
CLS - Common Language Specification. A type that is CLS compliant, may be used across
any .NET language. CLS is a set of language rules that defines language standards for a .NET
language and types declared in it.
IL - Intermediate Language, is the compiled form of the .NET language source code.
When .NET source code is compiled by the language specific compiler (say we compile C#
code using csc.exe), it is compiled to a .NET binary, which is platform independent, and is
called Intermediate Language code.
What is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET
framework.All Languages have runtime and its the responsibility of the runtime to take care
of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has
MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Following
are the responsibilities of CLR:
What is a CTS?
In order that two language communicate smoothly, CLR has CTS (Common Type
System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are
not compatible so the interfacing between them is very complicated. In order to able that two
different languages can communicate Microsoft introduced Common Type System. So
“Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is
datatype of CTS. CLS which is covered in the coming question is subset of CTS.
Note: If you have undergone COM programming period interfacing VB6 application with
VC++ application was a real pain as the datatype of both languages did not have a common
ground where they can come and interface, by having CTS interfacing is smooth.
This is a subset of the CTS which all .NET languages are expected to support. Microsoft has
defined CLS which are nothing but guidelines that language to follow so that it can
communicate with other .NET languages in a seamless manner.
What is a Managed Code?
Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are
managed code. But if you are using some third party software example VB6 or VC++
component they are unmanaged code as .NET runtime (CLR) does not have control over the
source code execution of the language.
What is a Assembly?
What is Manifest?
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the
following things (See Figure Manifest View for more details):
• Version of assembly
• Security identity
• Scope of the assembly
• Resolve references to resources and classes.
• The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft
intermediate language (MSIL) code or in a stand-alone PE file that contains only
assembly manifest information.
What is GAC ?
Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell,
where COM version was stored in central registry. So GAC should be used when absolutely
necessary.
Strong name is similar to GUID(It is supposed to be unique in space and time) in COM
components.Strong Name is only needed when we need to deploy assembly in GAC. Strong
Names helps GAC to differentiate between two versions. Strong names use public key
cryptography (PKC) to ensure that no one can spoof it.PKC use public key and private key
concept.
• How can we do Assembly versioning?
Assembly Versioning
All versioning of assemblies that use the common language runtime is done at the assembly
level. The specific version of an assembly and the versions of dependent assemblies are
recorded in the assembly's manifest. The default version policy for the runtime is that
applications run only with the versions they were built and tested with, unless overridden by
explicit version policy in configuration files (the application configuration file, the publisher
policy file, and the computer's administrator configuration file).
For more information about configuring applications, see Configuration Files. For more
information about binding policy, see How the Runtime Locates Assemblies.
Version Information
• The assembly's version number, which, together with the assembly name
and culture information, is part of the assembly's identity. This number is
used by the runtime to enforce version policy and plays a key part in the
type resolution process at run time.
• An informational version, which is a string that represents additional
version information included for informational purposes only.
For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version,
1254 as the build number, and 0 as the revision number.
The version number is stored in the assembly manifest along with other identity information,
including the assembly name and public key, as well as information on relationships and
identities of other assemblies connected with the application.
When an assembly is built, the development tool records dependency information for each
assembly that is referenced in the assembly manifest. The runtime uses these version
numbers, in conjunction with configuration information set by an administrator, an
application, or a publisher, to load the proper version of a referenced assembly.
The runtime distinguishes between regular and strong-named assemblies for the purposes of
versioning. Version checking only occurs with strong-named assemblies.
For information about specifying version binding policies, see Configuration Files. For
information about how the runtime uses version information to find a particular assembly, see
How the Runtime Locates Assemblies.
In this article we will try to understand what are the different events which takes place right
from the time the user sends a request, until the time request is rendered on the browser. So
we will first try to understand the two broader steps of an ASP.NET request and then we will
move in to different events emitted from ‘HttpHandler’, ‘HttpModule’ and ASP.NET page
object. As we move in this event journey we will try to understand what kind of logic should
go in each every of these events.
This is a small Ebook for all my .NET friends which covers topics like
WCF,WPF,WWF,Ajax,Core .NET,SQL etc you can download the same from
http://tinyurl.com/4nvp9t or else you can catch me on my daily free training @
http://tinyurl.com/y4mbsn6
From 30,000 feet level ASP.NET request processing is a 2 step process as shown below. User
sends a request to the IIS:-
• ASP.NET creates an environment which can process the request. In other words it creates
the application object, request, response and context objects to process the request.
• Once the environment is created the request is processed through series of events which is
processed by using modules, handlers and page objects. To keep it short lets name this step as
MHPM (Module, handler, page and Module event), we will come to details later.
In the coming sections we will understand both these main steps in more details.
Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve
this request. Depending on file extension the request is processed. For instance if the page is
an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.
Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’
creates an application domain where the website can run. As we all know application domain
creates isolation between two web applications hosted on the same IIS. So in case there is
issue in one app domain it does not affect the other app domain.
Step 3:- The newly created application domain creates hosting environment i.e. the
‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET
objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.
Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to
serve the request. In case you have a ‘global.asax’ file in your system then object of the
‘global.asax’ file will be created. Please note ‘global.asax’ file inherits from
‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of
‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’
instances might be reused for multiple requests.
Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to
process the page.
Step 6:- ‘HttpApplication’ then starts processing the request by http module events , handlers
and page events. It fires the MHPM event for request processing.
Note: - For more details http://msdn.microsoft.com/en-us/library/ms178473.aspx
Below image explains how the internal object model looks like for an ASP.NET request. At
the top level is the ASP.NET runtime which has creates an ‘Appdomain’ which in turn has
‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.
Step 1(M ? HttpModule):- Client request processing starts. Before the ASP.NET engine
goes and creates the ASP.NET ‘HttpModule’ emits events which can be used to inject
customized logic. There are 6 important events which you can utilize before your page object
is created
‘BeginRequest’,’AuthenticateRequest’,’AuthorizeRequest’,’ResolveRequestCache’,’Acquire
RequestState’ and ‘PreRequestHandlerExecute’.
Step 2 (H ? ‘HttpHandler’ ) :- Once the above 6 events are fired , ASP.NET engine will
invoke ‘ProcessRequest’ event if you have implemented ‘HttpHandler’ in your project.
Step 3 (P – ASP.NET page):- Once the ‘HttpHandler’ logic executes the ASP.NET page
object is created. While the ASP.NET page object is created many events are fired which can
help us to write our custom logic inside those page events. There are 6 important events
which provides us placeholder to write logic inside ASP.NET pages ‘Init’ , ‘Load’ , ‘validate’
, ‘event’ , ‘render’ and ‘unload’. You can remember the word ‘SILVER’ to remember the
events S – Start ( does not signify anything as such just forms the word ) , I – (Init) , L
( Load) , V ( Validate) , E ( Event) and R ( Render).
Step4 (M ? HttpModule):- Once the page object is executed and unloaded from memory
‘HttpModule’ provides post page execution events which can be used to inject custom post-
processing logic. There are 4 important post-processing events ‘PostRequestHandlerExecute’,
‘ReleaserequestState’, ‘UpdateRequestCache’ and ‘EndRequest’.
Below figure shows the same in a pictorial format.
In What event we should do what?
The million dollar question is in which events we should do what? . Below is the table which
shows in which event what kind of logic or code can go.
HttpModul PostRequestHandlerEx Any logic you would like to inject after the
e ecute handlers are executed.
With this article we have attached a sample code which shows how the events actually fire. In
this code we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have
displayed a simple response write in all events , below is how the output looks like.
Below is the class for ‘HttpModule’ which tracks all event s and adds it to a global collection.
{
objArrayList.Add("httpModule:OnUpdateRequestCache");
}
void OnReleaseRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnReleaseRequestState");
}
void OnPostRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPostRequestHandlerExecute");
}
void OnPreRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPreRequestHandlerExecute");
}
void OnAcquireRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAcquireRequestState");
}
void OnResolveRequestCache(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnResolveRequestCache");
}
void OnAuthorization(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAuthorization");
}
void OnAuthentication(object sender, EventArgs a)
{
objArrayList.Add("httpModule:AuthenticateRequest");
}
void OnBeginrequest(object sender, EventArgs a)
{
objArrayList.Add("httpModule:BeginRequest");
}
void OnEndRequest(object sender, EventArgs a)
{
objArrayList.Add("httpModule:EndRequest");
objArrayList.Add("<hr>");
foreach (string str in objArrayList)
{
httpApp.Context.Response.Write(str + "<br>") ;
}
}
}
Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.
{
clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");
context.Response.Redirect("Default.aspx");
}
}
We are also tracking all the events from the ASP.NET page.
public partial
class _Default : System.Web.UI.Page
{
protected void Page_init(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Init");
}
protected void Page_Load(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Load");
}
public override void Validate()
{
clsHttpModule.objArrayList.Add("Page:Validate");
}
protected void Button1_Click(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Event");
}
protected override void Render(HtmlTextWriter output)
{
clsHttpModule.objArrayList.Add("Page:Render");
base.Render(output);
}
protected void Page_Unload(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:UnLoad");
}}
Below is how the display looks like with all events as per the sequence discussed in the
previous section.
Zooming ASP.NET page events
In the above section we have seen the overall flow of events for an ASP.NET page request.
One of the most important section is the ASP.NET page, we have not discussed the same in
detail. So let’s take some luxury to describe the ASP.NET page events in more detail in this
section.
Any ASP.NET page has 2 parts one is the page which is displayed on the browser which has
HTML tags , hidden values in form of viewstate and data on the HTML inputs. When the
page is posted these HTML tags are created in to ASP.NET controls with viewstate and form
data tied up together on the server. Once you get these full server controls on the behind code
you can execute and write your own login on the same and render the page back to the
browser.
Now between these HTML controls coming live on the server as ASP.NET controls, the
ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on
what task / logic you want to perform we need to put these logics appropriately in those
events.
Note: - Most of the developers directly use the ‘page_load’ method for everything, which is
not a good thought. So it’s either populating the controls, setting view state, applying themes
etc everything happens on the page load. So if we can put logic in proper events as per the
nature of the logic that would really make your code clean.
View
Form
Controls state
Se data
Events Initialize What Logic can be written here?
q Availabl
d Availa
e
ble
In order to modularize/ define the functionality of a one class, that class can uses
functions/ properties exposed by another class in many different ways. According
to Object Oriented Programming there are several techniques, classes can use to
link with each other and they are named association, aggregation, and
composition.
There are several other ways that an encapsulation can be used, as an example we can take
the usage of an interface. The interface can be used to hide the information of an
implemented class.
Collapse
Abstract classes are ideal when implementing frameworks. As an example, let’s study the
abstract class named LoggerBase below. Please carefully read the comments as it will help
you to understand the reasoning behind this code.
Collapse
/// <summary>
/// protected, so it only visible for inherited class
/// </summary>
protected LoggerBase()
{
// The private object is created inside the constructor
logger = log4net.LogManager.GetLogger(this.LogPrefix);
// The additional initialization is done immediately after
log4net.Config.DOMConfigurator.Configure();
}
/// <summary>
/// When you define the property as abstract,
/// it forces the inherited class to override the LogPrefix
/// So, with the help of this technique the log can be made,
/// inside the abstract class itself, irrespective of it origin.
/// If you study carefully you will find a reason for not to have “set”
method here.
/// </summary>
protected abstract System.Type LogPrefix
{
get;
}
/// <summary>
/// Simple log method,
/// which is only visible for inherited classes
/// </summary>
/// <param name="message"></param>
protected void LogError(string message)
{
if (this.logger.IsErrorEnabled)
{
this.logger.Error(message);
}
}
/// <summary>
/// Public properties which exposes to inherited class
/// and all other classes that have access to inherited class
/// </summary>
public bool IsThisLogError
{
get
{
return this.logger.IsErrorEnabled;
}
}
}
The idea of having this class as an abstract is to define a framework for
exception logging. This class will allow all subclass to gain access to a common
exception logging module and will facilitate to easily replace the logging library.
By the time you define the LoggerBase, you wouldn’t have an idea about other
modules of the system. But you do have a concept in mind and that is, if a class
is going to log an exception, they have to inherit the LoggerBase. In other word
the LoggerBase provide a framework for exception logging.
Like any other class, an abstract class can contain fields, hence I used a private field named
logger declare the ILog interface of the famous log4net library. This will allow the
Loggerbase class to control, what to use, for logging, hence, will allow changing the source
logger library easily.
The access modifier of the constructor of the LoggerBase is protected. The public constructor
has no use when the class is of type abstract. The abstract classes are not allowed to
instantiate the class. So I went for the protected constructor.
The abstract property named LogPrefix is an important one. It enforces and guarantees to
have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class, which the
exception has occurred) for every subclass, before they invoke a method to log an error.
The method named LogError is protected, hence exposed to all subclasses. You are not
allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase
cannot use it meaningfully.
Let’s find out why the property named IsThisLogError is public. It may be important/ useful
for other associated classes of an inherited class to know whether the associated member logs
its errors or not.
Apart from these you can also have virtual methods defined in an abstract class. The virtual
method may have its default implementation, where a subclass can override it when required.
All and all, the important factor here is that all OOP concepts should be used carefully with
reasons, you should be able to logically explain, why you make a property a public or a field
a private or a class an abstract. Additionally, when architecting frameworks, the OOP
concepts can be used to forcefully guide the system to be developed in the way framework
architect’s wanted it to be architected initially.
Ability of a new class to be created, from an existing class by extending it, is called
inheritance.
Collapse
According to the above example the new class (IOException), which is called the derived
class or subclass, inherits the members of an existing class (Exception), which is called the
base class or super-class. The class IOException can extend the functionality of the class
Exception by adding new types and methods and by overriding existing ones.
Just like abstraction is closely related with generalization, the inheritance is closely related
with specialization. It is important to discuss those two concepts together with generalization
to better understand and to reduce the complexity.
One of the most important relationships among objects in the real world is specialization,
which can be described as the “is-a” relationship. When we say that a dog is a mammal, we
mean that the dog is a specialized kind of mammal. It has all the characteristics of any
mammal (it bears live young, nurses with milk, has hair), but it specializes these
characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As
such, we expect it to share certain characteristics with the dog that are generalized in
Mammal, but to differ in those characteristics that are specialized in cats.
The specialization and generalization relationships are both reciprocal and hierarchical.
Specialization is just the other side of the generalization coin: Mammal generalizes what is
common between dogs and cats, and dogs and cats specialize mammals to their own specific
subtypes.
Similarly, as an example you can say that both IOException and SecurityException are of
type Exception. They have all characteristics and behaviors of an Exception, That mean the
IOException is a specialized kind of Exception. A SecurityException is also an Exception. As
such, we expect it to share certain characteristic with IOException that are generalized in
Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In
other words, Exception generalizes the shared characteristics of both IOException and
SecurityException, while IOException and SecurityException specialize with their
characteristics and behaviors.
In OOP, the specialization relationship is implemented using the principle called inheritance.
This is the most common and most natural and widely accepted way of implement this
relationship.
At times, I used to think that understanding Object Oriented Programming concepts have
made it difficult since they have grouped under four main concepts, while each concept is
closely related with one another. Hence one has to be extremely careful to correctly
understand each concept separately, while understanding the way each related with other
concepts.
In the software world, though you may not have realized it, you have already used classes.
For example, the TextBox control, you always used, is made out of the TextBox class, which
defines its appearance and capabilities. Each time you drag a TextBox control, you are
actually creating a new instance of the TextBox class.
• What is Inheritance?