You are on page 1of 29

1

A Guide to .net
Introduction to .NET Framework

You can make use .Net Framework as a development environment


or a platform for developing user friendly web-based applications
that can allow seamless access by users from any where in the
world and from any type of client machines. You can apply the
open standards such as XML (eXtensible Markup Language), SOAP
(Simple Object Access Protocol) and HTTP (HyperText Transfer
Protocol) for developing your web-applications and web
applications created with such open standards can interact well
with other applications of other platforms.

You can use different programming languages such as C#,


VBScript, VB.NET, Managed C++ for developing your applications
in .NET Framework, as the .NET Framework is not dependent on
one particular language or platform and can support many kinds
of platforms and programming languages that are in use today.
Further, you can use .NET Framework for running your
applications in almost all platforms such as Linux, Macintosh and
Unix without any hitches.

The presence of many off-the-shelf libraries in .NET Framework


can assist you in developing your applications in a faster, cheaper
and easier manner. The most recent .Net Framework version is
capable of supporting over 20 different programming languages
today.

The functionality of .Net Framework supporting many


programming languages is due to the use of the powerful CLR,
the Common Language Runtime engine. The application
programming codes are first compiled by CLR into a Microsoft
Intermediate Language (MSIL) code instead of native codes and
the MSIL, which is nothing but an instruction set, in turn creates
the native code for running the application.

The main advantage of language and platform independent


feature of .NET Framework can be attributed to CLR and the same
CLR also takes care of run-time services such as memory
2

processes, security enforcement, integration of language, and


thread management. Hence, you can make use of the various
infrastructures that have been provided in .NET Framework for
creating your web-applications.

As per the classification by the Microsoft, there are two categories


of .NET Framework and they are CLR and .Net Framework class
library.

Common Language Runtime: The CLR is responsible for providing


a common runtime environment or services with which all .NET
applications can run. Further, the various capabilities of CLR can
enable any developer to write even big applications with ease
using the features such as strong type naming, life-cycle
management, dynamic binding that is capable of making any
business logic into re-usable component and finally the cross-
language exception handling.

.Net Framework class library: This class library constitutes various


predefined functional sets that are very useful while developing
the applications by developers. There are three main components
in this class library and they are:

· ASP.NET.
· Windows Forms.
· ADO.NET.

With the .Net Framework you can make your codes written in
fewer lines and other favourable features such as easy web
settings, easy deployment of applications, easy compilation
procedures, easy Web configuration makes the .NET Framework a
great platform to work with. In an overall scenario, the developers
will be able to concentrate more on Web controls and spend an
efficient time in application design and implementation and to
have an effective control over the flow of the application
sequence.

Another great feature that any developer can take note of is the
feature of .NET Framework taking into cognisance all the Web
controls, server-side blocks of codes and Web forms and getting
3

them compiled whenever a call for the page compilation is


completed.

Once the components of .NET framework are compiled in your


machine, the compiled version can easily be uploaded with all the
relevant pages in the /bin directory of the system. The process of
uploading is very easy when compared to the complicated
process of web-application in ASP, where in you have to first
upload the application pages with the relevant components and
you also need to register them with the operating system.

In .NET Framework the simple uploading in /bin directory of the


operating system is enough and you need not carry out the
complicated process of registering the components of web-
application with the operating system.

With the help of an XML based web.config file you can carry out
the web settings which is nothing but configuring the .NET
applications for successful running. The XML based web.config file
can be modified through a program and when any such
modification is done, the system recognises the change and
registers it immediately that makes configuration of .NET
applications easy and quick.

Caching is a process or a method with which the most commonly


and frequently used resources and data will get loaded onto the
memory for easy and fast access. There are three types of
caching in .Net Framework and they are output caching, data
caching, and fragment caching.

Understanding Globalization in .NET

Globalization refers to the process with which an application or


software will be designed and developed so as to make it run
across all platforms and all sites with minimum or no modification
to the software application. The software is very amenable to
customisation so as to suit to the location-specific conditions and
it is also capable of providing information based on the varied
inputs and the location-specific operating system.
4

Under any normal circumstance, there will be two processes in


Globalization and they are customisation or localisation of the
application and internationalizing the application codes so as to
meet the standards of the local culture and other related matters.

In internationalization process the application code base will be


same and the efforts will be on jobs such as translating, storing,
retrieving and to make the application user friendly for the
selected locale. In any given place the culture and the language
will always be different and besides this you should also take into
account the other factors such as time zone, normal date pattern
usage, cultural and language environments, currencies, telephone
numbers, and so many other factors that are specific to the
locale.

In globalization the process of internationalization enables you to


remove from the code base and the presentation layer all the
contents and make you to use only a single presentation layer
and single code base with a common contents that can suit any
culture. The internationalization process will aid you to keep all
the contents in a common place with an idea of making it easily
accessible by the programme codes and the results can easily be
populated all over presentation layer and the application with
ease and efficiently.

In addition to the above, the internationalization process also


enables you to store the contents and all the collected inputs from
the user in a user friendly format and in a highly secured manner
without compromising any standards pertaining to the local
culture. The internationalization process is one step before any
attempt for localising the application to suit to the local needs.

With the help of the localization process of globalization, you can


make your application adaptable to the various location specific
conditions and it will be easy for you to translate and re-format
your application to suit to your new location and that too without
changing any of the codes. Further, you can make use of the
process for rectifying any of the reported bugs and for fine tuning
the application for running smoothly without any hitch.
5

The globalization process also makes use of the locally prevailing


information on culture where the software or the application is to
be installed and maintained. The locational details and the
language used in that particular area constitute to culture
information and for working with any culture based information
the namespace concept is utilised and the SystemGlobalization,
SystemResources and SystemThreading are the available
namespaces in .NET Framework.

Out of the various namespaces, the SystemGlobalization


namespace constitute classes that are used to hold information
relating to region or country, the local language used, type of
calendars, date format used, numbers, currency, etc., all in a
meticulously arranged fashion and all these classes are used
while developing the globalized (internationalized) applications.

You can use advanced globalization functionalities with the


assistance of classes such as StringInfo and TextInfo classes and
the various functionalities include text element processing and
surrogate support systems.

The SystemResources namespace constitutes interfaces and


classes that are very helpful for developers and maintenance
experts in creating, storing, retrieving, and managing various
resources used in the application that are culture and location-
specific.

The SystemThreading namespace constitutes interfaces and


classes that aid in multithreaded programming. The classes that
are used in this type of SystemThreading namespace are also
useful in accessing data and for synchronization of thread
activities.

About Just in time (JIT) compiler in .NET

The high level programming languages that need to be compiled


require a runtime, so that the architecture on which the language
runs is provided with details on how to execute its code. All the
programming languages use its corresponding runtime to run the
application. For example, to run an application developed using
6

Visual Basic, the computer on which the application will be run


must be installed with the Visual Basic runtime. The Visual Basic
runtime can run only the applications developed with Visual Basic
and not the ones developed with any other programming
language like Java.

In the .NET Framework, all the Microsoft .NET languages use a


common language runtime, which solves the problem of installing
separate runtime for each of the programming languages.
Microsoft .NET Common Language Runtime installed on a
computer can run any language that is Microsoft .NET compatible.

The main advantage of the .NET Framework is the interoperability


between different languages. As all the Microsoft .NET languages
share the same common runtime language, they all work well
together. For example, you can use an object written in C# from
Visual Basic.NET. The same applies for all the other Microsoft .NET
languages.

When you compile a Microsoft.NET language, the complier


generates code written in the Microsoft Intermediate Language
(MSIL). MSIL is a set of instructions that can quickly be translated
into native code.

A Microsoft.NET application can be run only after the MSIL code is


translated into native machine code. In .NET Framework, the
intermediate language is complied "just in time" (JIT) into native
code when the application or component is run instead of
compiling the application at development time. The Microsoft.NET
runtime consists of two JIT compilers. They are standard JIT
compiler and the EconoJIT compiler. The EconoJIT compiler
compiles faster than the standard JIT compiler, but the code it
produces is not as optimized as the code obtained from the
standard JIT compiler.

About ASP.NET Assemblies in .Net

An assembly in ASP.NET is a collection of single-file or multiple


files. The assembly that has more than one file contains either a
dynamic link library (DLL) or an EXE file. The assembly also
7

contains metadata that is known as assembly manifest. The


assembly manifest contains data about the versioning
requirements of the assembly, author name of the assembly, the
security requirements that the assembly requires to run, and the
various files that form part of the assembly.

The biggest advantage of using ASP.NET Assemblies is that


developers can create applications without interfering with other
applications on the system. When the developer creates an
application that requires an assembly that assembly will not affect
other applications. The assembly used for one application is not
applied to another application. However one assembly can be
shared with other applications. In this case the assembly has to
be placed in the bin directory of the application that uses it.

This is in contrast to DLL in the past. Earlier developers used to


share libraries of code through DLL. To use the DLL that is
developed by another developer for another application, you have
to register that DLL in your machine. In ASP.NET, the assembly is
created by default whenever you build a DLL. You can check the
details of the manifest of the assembly by using classes located in
the System.Reflection namespace.

Thus you can create two types of ASP.NET Assemblies in ASP.NET:


private ASP.NET Assemblies and shared assemblies. Private
ASP.NET Assemblies are created whey you build component files
like DLLs that can be applied to one application. Shared ASP.NET
Assemblies are created when you want to share the component
files across multiple applications. Shared ASP.NET Assemblies
must have a unique name and must be placed in Global Assembly
Cache (GAC). The GAC is located in the Assembly directory in
WinNT. You can view both the manifest and the IL using
ILDisassembler (ildasm.exe).

.NET Assemblies - I

This article is going to be based on three parts.

1. In the first part we will be discussing the 3-tier architecture.


8

2. In part-II of this article we will see what the .NET assemblies


are and
3. In the last part we will be practically implementing a simple
.NET assembly.

Part-I :: The Three-Tier Architecture

A 3-tier architecture defines the division of a web based


application into three layers. When we say 3-tier architecture, we
are actually meaning the number of nodes (or computers) that
are involved within the communication. Let's first of all see what
do I mean when I say a 3-tier architecture or a n-tier architecture.

For example, consider a simple scenario in which we have a


client/server architecture. A user simply connects with the server
and communication starts. The server fulfills all the requirements
of the client as all of the contents have been placed on the server.
This type of architecture is called as a client/server architecture or
it can also be said as a two-tier architecture.

In a two-tier architecture the server contains all the contents that


would be requested from the client, the contents can include web
pages, the server-side technology implemented and the data-
store. If we separate the contents of the server-side technology
from the web pages and place them on a separate machine then
this architecture would become a three-tier architecture. Similarly
if we keep on increasing the number of machines in between our
client/server communication then we would be implementing the
n-tier architecture for our communication.

Why do we need the three-tier architecture?

The three-tier architecture was introduced for better management


of code and contents and to improve the performance of the web
based applications. Within the three-tier architecture we divide
our application into a set of three layers.

4. Presentation
5. Business Logic
6. Database
9

The first layer Presentation contains the interface code,


that is going to be displayed to the user. This code could
contain any technology that can be used on the client side
like HTML, JavaScript or VBScript etc.
The second layer Business Logic contains all the code of
the server-side technology. This layer mainly contains the
code that is used for accessing the database and to query,
manipulate, pass data to user interface and handle any input
from the UI as well.
The third and last layer Data represents the data store like
MS Access, SQL Server, an XML file, an Excel file or even a
text file containing data.

The following diagram shows the layers we have just described.

(Figure Displaying the layers of the three-tier architecture)

One of the main benefits of the three-tier architecture is easy


management of the contents of the web application. Consider a
scenario in which you require to change the presentation of the
web pages because you have recently designed a new look for
your website. In the case of two-tier architecture you would
require to change the web pages that would be containing both
the contents for the presentation as well as the business logic,
this would mean an headache for you to keep the code for
business logic as it is and change the code for the presentation
layer. In case of a three-tier architecture the code of the business
logic would be residing on the middle layer, there for you would
be requiring only to make a change on the presentation layer
containing the code for your web page designs.Similarly if you
require to change the database system for example, from Access
to Sql Server, then you would require only to change the database
10

on the data server without having to make any changes within the
code of your business logics.

The three-tier application design also enables for better


performing web applications, since the whole load of users is not
placed upon a single server. As we can see in the figure displaying
the design of a three-tier architectured web application, it can be
seen that placing the business logic and the database on the
different machines reduces the load upon a single server.
Similarly we can implement any number of servers we like on the
backend of the application and such an architecture would be
known as n-tier architecture.

.NET Assemblies - II

This is a three series article.

1. In the first part we discussed the 3-tier architecture.


2. In part-II of this article we will see what the .NET assemblies
are and
3. In the last part we will be practically implementing a simple
.NET assembly.

Part-II :: Introduction to .NET Assemblies

ASP .NET introduces many techniques for better code


management and code reusability. Code Behind and Custom
Controls are one of the best implementations of these
techniques where you can separate your HTML tags and coding
from your server-side script. It also provides future facilities to
manage the code easily.

The Code Behind and Custom Controls development is a good


approach to better web development, but there is a performance
hit that also exists. You may know about the CLR (Common
Language Runtime), I will not go into the detail of this, but just
for a brief introduction, it is the "black box" or the "heart" of the
.NET where the compilation of your code takes place. Whenever
an ASP .NET page is opened or requested by the user, the page
gets compiled first and then is transferred to the user. The
11

compilation process is also completed in two steps. First of all an


IL (Intermediate Language) is generated and then this is
handed over for JIT (Just In Time) compilation which produces
the machine code and our pages get displayed with their dynamic
content.

The performance of our web application can be improved by


creating pre-compiled libraries of IL which can then be handed
over to JIT directly without having the inclusion of an extra
process to make the conversion. This method is called
componentization. Components are pre-compiled set of classes
that have been developed in the form of DLL files and can then
be included within our projects. This is also known as an
assembly.

"An assembly is a logical grouping of functionality in a


physical file."

Understanding the assemblies and their concepts is the focus of


this article. An assembly has many benefits some of which are.

4. Increased performance.
5. Better code management and encapsulation.
6. Introduces the n-tier concepts and business logic.

You might have heard of the n-tier and three-tier architecture


concepts. (To know about the detail of 3-tier architectural
concepts please read Part-I of this article.). The practical
implementation of the three-tier architecture is also implemented
by using the assemblies. In the first part of this article we
discussed about the Business Logic layer. This layer is where we
place all the business rules that apply to the transactions that
take place between the client and the server, and this layer is
implemented through components. The reason for this is that one
we hide our code and the business rules that have been applied
(since the components are in compiled binary form, so they are a
mean of code encapsulation) and second because they are more
efficient (since the code is already transferred into IL therefore
only the JIT compilation takes place instead of both the IL and
JIT).
12

.NET Assemblies - III

This is a three series article.

1. In the first part we discussed the 3-tier architecture.


2. In part-II of this article we had an introduction to what the
.NET assemblies are? and
3. In the last part we are practically going to be implementing a
simple .NET assembly.

Part-III :: Implementing a simple .NET Assembly

This part of the article is going to be the last of the series. In the
last part I introduced you to what the .NET Assemblies are and for
what reasons are they used? You also were informed about the
advantages of using the .NET Assemblies as compared to the
other scripting techniques that we have available in the ASP .NET.

Before implementing an assembly I would like to add, that we


implement many pre-built assemblies while we are working on
ASP .NET based applications. For example; the System
namespace and other namespaces like it i.e. System.Data,
System.Web are also pre-built assemblies that have been
provided in the .NET framwork to us by Microsoft. In addition to
this they have also provided us the capability of making our own
assemblies. As compared to the classic ASP making components
in form of assemblies in ASP .NET is much more easier and
flexible.

Now let's go ahead with creating our first component. This is


going to be a simple component that would just provide us with a
few options to display a message on the screen. Write the
following code in Notepad or any other editor that you have.

Imports System

Namespace HRM.Display
Public Class DisplayConsole

Public Function Welcome() As String


13

Return "Welcome to your first component!"


End Function

Public Function Output(strParam As String) As String


Return strParam
End Function

End Class
End Namespace

Save this file by the name "hrmDisplay.vb".

Now for the process of converting this file into a compiled DLL
file, we require to make a batch file. Again open the Notepad and
add the following to it. Save the following file by name
"MakeComponent.bat"

set indir=c:\inetpub\wwwroot\hrmDisplay.vb
set outdir=c:\inetpub\wwwroot\bin\hrmDisplay.dll
set assemblies=System.dll
vbc /t:library /out:%outdir% %indir% /r:%assemblies%

Before running the file you require to create a directory by the


name of bin. Create a directory in your current directory by name
of bin and then run the file. Checkout the bin directory your DLL
file would be placed there after its creation.

Before using the component we require to do one more thing! and


that is to make a web.config file. Web.config is an XML based
file that specifies important configuration for an ASP .NET
application. Again open up the Notepad and write the following
code.

<configuration>
<system.web>
<sessionState timeout="10" />
<compilation>
<assemblies>
<add assembly="hrmDisplay" />
14

</assemblies>
</compilation>
</system.web>
</configuration>

Save this file as "web.config". The reason that we made the bin
directory and then placed the DLL file within it was that the
web.config would always search for the file in the bin directory,
not only this assembly, but other user defined and third party
assemblies also require there references to be added into the
web.config.

Now we are ready to use our component within our ASP .NET
page. Open up Notepad or any other editor and add the
following code into the file and save it as "Test.aspx".

<%@ Import Namespace = "HRM.Display" %>


<%@ Page Language = "VB" %>

<Script Language="VB" Runat="Server">

Sub Page_Load(Source As Object, Sender As EventArgs)

Dim objComponent As New DisplayConsole

Response.Write (objComponent.Welcome())
<br>
Response.Write (objComponent.Output("This is my message!"))

End Sub

</Script>

Now open your page in Internet Explorer or any other browser


through your server and see your component in action.

Understanding User Controls in .NET Framework

Though you can apply multiple server controls in your web form,
ASP.NET allows you to create new controls according to your
15

requirements. The controls that you create are called ASP.NET


User Controls. ASP.NET User Controls have .ascx extension. The
biggest advantage of ASP.NET User Controls is that it allows you
to save a part of the web form and reuse it many other web
forms. This drastically reduces the developers’ time.

ASP.NET User Controls are self-contained entities that are saved in


an independent file. You can relate a user control with a “black
box”. ASP.NET User Controls are very helpful when you want to
use functionality on multiple pages of a web-application. For
example, if you want to use a site navigation header or footer on
all the pages of the web application, you can create this site
navigation header or footer as a user control in a separate page.
You do not need to place this user control on each and every
page. You just have to write a few lines code to call the user
control.

As ASP.NET User Controls are self-contained the developers


working on the same project need not worry about transgressing
on other’s code. ASP.NET User Controls offer a great deal of
functionality than Server-side Includes (SSIs). Using SSIs in
encapsulating the site functionality is a quite tedious task when
compared to ASP.NET User Controls. You can create a user control
by using the Register directive. This process is called registering
the user control. For instance, you can use this code to register a
user control:

<%@ Register TagPrefix="sampNamespace"


TagName="Myname" Src="mypage.ascx" %>

The TagPrefix is the exclusive namespace provided to the user


control so that multiple ASP.NET User Controls with similar name
can be discriminated from each other. The TagName is the name
of the user control and the Src is the virtual path to the user
control. After registering the user control you can place the tag of
the user control in an appropriate location on the web form. You
have to include the runat=”server” attribute with the tag.

You can create a user control using only one programming


language for a web form. However, you can create multiple
16

ASP.NET User Controls for a web form. For example, you can
create a user control using C# and another user control using
VB.NET and use both the ASP.NET User Controls on the same web
form.

About Web Forms in .NET Framework

Web pages in ASP.Net are called ASP.NET Web Forms which have
certain server controls such as text, dropdown list, checkboxes,
and buttons. An ASP.NET Web Form looks similar to the web forms
in HTML. The only difference is that in ASP.NET, the Web Forms
runs at the server side and in HTML the web forms runs at the
client side. Apart from this difference an ASP.NET Web Form has
more features than an ordinary HTML web form such as:

• The code blocks are processed on the server.


• The entire page in ASP.NET is compiled when it is requested for
the first time. When you make subsequent requests, the page is
not compiled but shown directly in your browser.
• ASP.NET Web Forms can contain page directives. Page directives
allow you to set the default language and user controls tags for
the entire page. You can also turn off session state and ViewState
management using page directives.
• An ASP.NET Web Form can contain both user controls and Server
side Includes (SSIs).
• An ASP.NET Web Form though run on the server can contain
client side script such as JavaScript or Jscript.

An ASP.NET Web Form first gets compiled into Intermediate


Language (IL) and later to the machine language. Not just the
server side code gets compiled but every control and element in
the page gets compiled. This enables the ASP.NET Web Form to be
in any language that is compatible with Common Language
Runtime (CLR) engine. Another advantage with the code getting
translated to IL is that the user can use the application in any
browser. In addition, you can reduce the processors and server’s
load when you compile the ASP.NET Web Forms in ASP.NET,
thereby, increasing the user’s productivity time. Thus ASP.NET
allows you to create Web Forms that are platform independent,
language independent, and browser independent.
17

Access Control List in .NET Framework

Once you complete developing a web application, you need to


secure it. This is when the aspect of security comes into picture.
There will be some portions of your application which need to be
secured from users. Securing an application may need extra
hardware to build complex multi-layer systems with firewalls, and
also some highly secure features. Security enables you to provide
access to a specified user after the user is authenticated and
authorized to access the resources in your web application. The
Access Control List is used in the authorization process.

The basic concepts of security are Authentication, Authorization,


Impersonation and Data or functional security. Authentication is
the process that enables to identify a user, so that only that user
is provided access to the resources. Authorization is the process
that enables to determine whether a particular user can be given
access to the resources that the user requests. Impersonation is
the process that provides access to resources requested by a user
under a different identity. Data or functional security is the
process of securing a system physically, updating the operating
system and using robust software.

Some elements of an operating system, the Internet Information


Server (IIS), and the .NET Framework work in coordination to
provide the features required to execute the security concepts
mentioned above. For example, Windows 2000 uses its own list of
user accounts for identifying and authenticating users. IIS
identifies the users based on the information provided by
Windows, when the users access a web site. IIS after identification
of the users, passes this information to ASP.NET. Then the user
information is checked for authorization.

To restrict access to the users for certain resources of an


application, a process of identifying the users becomes a
necessity. Authentication enables to restrict a user to access the
resources by certain ways. It could be a combination of a
username and password, a digital certificate, a smart card or a
fingerprint reader. The validity of the information provided by the
user helps identify the user, so that the user is provided access to
18

the requested resources. The process of successful identification


of the user implies that the user is authenticated.

After identification of the user is over, the next step is to


determine whether the authenticated user has access to the
resources. The process of determining the access to the resources
for a particular user is known as Authorization. In Windows based
systems, resources have an Access Control List, which provides a
list of users who have access to that resource. The list also
specifies the kind of access such as read, write, modify, and
delete the resource, for each user. For example, if a user requests
an ASP page, the operating system checks whether the user has
Read access to the page and if the user has read permission, then
the operating system allows the IIS to fetch the page. The IIS has
authorization settings which enable the IIS to control the access of
resources by users. File Access Control Lists are set for a given file
or directory using the Security tab in the Explorer property page.

Understanding ASP.NET Validation Controls

After you create a web form, you should make sure that
mandatory fields of the form elements such as login name and
password are not left blank; data inserted is correct and is within
the specified range. Validation is the method of scrutinizing that
the user has entered the correct values in input fields. In HTML
you can perform validation either by checking the values at client-
side or after submitting the form at the server-side. But these
methods in HTML take lots of time to create and maintain the
code. Moreover, if the user has disabled JavaScript then he or she
may not receive the message regarding the error.

Therefore, in ASP.NET you can use ASP.NET Validation Controls


while creating the form and specify what ASP.NET Validation
Controls you want to use and to which server control you want
bind this. ASP.NET Validation Controls are derived from a common
base class and share a common set of properties and methods.
You just have to drag and drop the ASP.NET Validation Control in
the web form and write one line of code to describe its
functionality.
19

This reduces the developer time from writing JavaScript for each
type of validation. Moreover, through ASP.NET Validation Controls
if any invalid data is entered the browser itself detects the error
on the client side and displays the error without requesting the
server. This is another advantage because it reduces the server
load.

The five types of ASP.NET Validation Controls in ASP.NET


Framework include:

• RequiredField Validation control: prompts message if any input


field is left blank. This validation control can also be used to
prompt message to the user if he or she has left any input field
with its default value.

• Range Validation control: Prompts message to the user, if the


data entered in the input field is not within the range of the
values specified by the Maximum and Minimum properties of the
validation control.

• Comparison Validation control: Allows the user to compare two


values and check for comparisons such as equality, greater-than,
less-than etc. In addition you can check whether the data entered
in the input field is of the data type as specified by you.

• RegularExpression Validation control: Allows you to validate if


the format of a certain input field is correct or not. You can check
the validation of the commonly performed formats such as social
security numbers, e-mail addresses, telephone numbers, and
postal code.

• Custom Validation control: Allows you to define your own


condition for validating the data in the input fields. Two validation
functions can be performed using Custom Validation control: first
on the server-side and second on the client-side. These functions
contain logic defined by you to validate the input fields. These
functions returns the True value and False value, if the condition
you specified is correct or not respectively.
20

If the control’s value does not validate to what you have specified
in the validation control tag, the web form displays an error
message. Moreover, you can customize the format of the error
message by using the control properties such as BackColor,
BorderStyle, and BorderWidth. In addition, you can use Cascading
Style Sheet (CSS) to format an error message.

Understanding ASP.NET Web Server Controls

ASP.NET Web Server Controls are controls that run at the web
server. All ASP.NET Web Server Controls can be identified by their
attribute ‘runat=”server”’. ASP.NET Web Server Controls are
similar to HTML controls. The only difference is that HTML controls
run at the client-side and the developers have to write the code
for each type of browsers. The ASP.NET Web Server Controls run
at the server-side and automatically adapt to the type of browser
that request it.

ASP.NET Web Server Controls also encapsulates and generates


large amount of HTML tags, thereby allowing the developers time
to concentrate on coding. ASP.NET Web Server Controls makes
exhaustive use of ViewState management. This makes data and
values to be consistent across ASP.NET pages.

All web controls are obtained from a common base class. This
ensures that the object model remains consistent across various
controls. For example, in order to move the cursor consistently
across a form you can specify the Web control TabIndex property.
This is very difficult while using normal HTML. You can also disable
a particular web control by exposing the Enabled property. This
process is also difficult in HTML and ASP.

ASP.NET ASP.NET Web Server Controls consists of Web form


controls, List controls, and Rich controls. All the web form controls
are defined within the namespace System.Web.UI.WebControls.
This namespace is a collection of classes that enables you to
create new ASP.NET Web Server Controls. The controls that you
can use web form controls category are button control, checkbox
control, radiobutton control, table control, image control, label
control, and panel control. These web form controls have a
21

common set of properties that can be used across multiple


controls.

The controls listed in the List controls category are dropdown list
control, repeater control, datalist control, and datagrid control.
These controls use the concept of data binding. The controls listed
in the Rich controls category include calendar control and
adrotator control. These controls are specifically being employed
for complex tasks.

Understanding WSDL and UDDI

Web Services Description Language (WSDL) is one of the prime


specifications in web services, the other two being SOAP and
UDDI. WSDL is the description language for web services that
describes a set of SOAP messages and how these messages are
exchanged across network. WSDL will be in XML format; therefore
it can be easily understood and edited by humans and machines.

Another advantage of WSDL being in XML format is that it is


programming language independent and also platform
independent. In addition, WSDL defines where the web service is
available from and what communications protocol has been used
to talk to the web service. As a result the WSDL file describes
everything that is required to write a program for an XML Web
service. There are tools available in Microsoft Visual Studio .NET
to read a WSDL file and generate the code required to
communicate with an XML Web service.

Universal Discovery Description Language (UDDI) is a directory


where you can expose your web services for other users to easily
access it. You can also consume the web service that is already
posted in UDDI. However, you can also post a web service without
registering it in UDDI. DISCO is another directory where you can
post your web service. But if you want to reach to maximum of
customers, you can place it in UDDI. The UDDI directory offers
three parts for you to register:
22

• White Pages
• Yellow Pages
• Green Pages

The white pages consist of the description such as name and


address of the company offering the service. The yellow pages
consist of industrial categories based on standard taxonomies
such as North American Industry Classification System and
Standard Industrial Classification. The green pages describe the
interface to the web service in detail so that anyone can write an
application after using the web service. Web services are
described in UDDI directory through a document called Type
Model or tmodel. Normally, this tModel contains a WSDL file that
describes a SOAP interface to an XML Web service, but the tModel
is flexible enough to describe almost any kind of web service.

Apart from using the web services from UDDI, you can also search
a particular web service in UDDI. In addition, you can search for
companies’ information that posted web services. In certain
times, you might know the names of the companies that offer
web services but you may not be aware of the web services that
they offer. The WS Inspection is a specification in UDDI that allows
you to search for a collection of web services that are located in a
particular company name. You can evaluate these web services
according to your requirements.

Understanding Impersonation in ASP.NET

At times users access a resource as though they were someone


else. This is known as impersonation. For example, if a web page
has no access controls, then any user can access that web page.
HTML pages, ASP pages, and components in version 3.0 and
earlier can be accessed through two accounts named
IUSR_machinename and IWAM_machinename. Both the accounts
are set up during IIS installation, and are automatically added to
all the folders in every web site on the server.

Anonymous access to a resource in IIS makes the task of


identifying a user extremely difficult. But there is no need to
authenticate a user in the case of IIS. When IIS receives a request
23

for a web page or other resource that has permission for


anonymous access, IIS treats the IUSR_machinename account as
the user's account, to access the resources. If the resource
requested by the user is an ASP page that uses a COM or COM+
component, that component is executed using the
IWAM_machinename account.

In ASP.NET, when impersonation is turned off, the resources can


be accessed using a "local system process" account. When
impersonation is turned on, ASP.NET executes every resource
using the account of a specified user who is authenticated when
the user makes the request. If you specify the IUSR_machinename
account to be used as the user account, then ASP.NET will behave
like previous versions of ASP, in providing access to the resources.

In ASP.NET, you first need to check whether the application is


configured to use impersonation. In the case of IIS, the IIS
impersonates users with its own IUSR account. In the case of
ASP.NET, impersonation is used to decide whether the user's
request should be executed using the account of the requested
user, or that of a local system-process account that ASP.NET uses
for anonymous requests.

The concept of impersonation is complex to some extent due to


the fact that ASP.NET uses the dynamic compilation features of
the .NET Framework. The IUSR account has only limited
permissions on the local machine, and so is not suitable without
some reconfiguration. This account is also used by IIS to access
resources like HTML pages, documents, and zip files that are not
executed as part of the .NET Framework.

If impersonation is enabled in an ASP.NET application then:


• If anonymous access is enabled in IIS, the request is made using
the IUSR_machinename account.
• If anonymous access is disabled in IIS, the request is made
using the account of the authenticated user.
• In either case, permissions for the account are checked in the
Windows Access Control List (ACL) for the resource(s) that a user
requests, and a resource is only available if the account they are
running under is valid for that resource.
24

If impersonation is disabled in an ASP.NET application then:


• If anonymous access is enabled in IIS, the request is made using
the system-level process account.
• If anonymous access is disabled in IIS, the request is made
using the account of the authenticated user.
• In either case, permissions for the account are checked in the
Windows ACL for the resource(s) that a user requests, and a
resource is only available if the account they are running under is
valid for that resource.

Basic use of Session in ASP.NET (C#):

STORE:
DataSet ds = GetDataSet(whatever parameters);
Session["mydataset")=ds;

RETRIEVE:
DataSet ds = (DataSet)Session["mydataset"];

Storage location

• InProc - session kept as live objects in web server


(aspnet_wp.exe). Use "cookieless" configuration in
web.config to "munge" the sessionId onto the URL (solves
cookie/domain/path RFC problems too!)
• StateServer - session serialized and stored in memory in a
separate process (aspnet_state.exe). State Server can run on
another machine
• SQLServer - session serialized and stored in SQL server

Performance

• InProc - Fastest, but the more session data, the more


memory is consumed on the web server, and that can affect
performance.
• StateServer - When storing data of basic types (e.g. string,
integer, etc), in one test environment it's 15% slower than
InProc. However, the cost of serialization/deserialization can
affect performance if you're storing lots
25

of objects. You have to do performance testing for your own


scenario.
• SQLServer - When storing data of basic types (e.g. string,
integer, etc), in one test environment it's 25% slower than
InProc. Same warning about serialization as in StateServer.

Performance tips for Out-of-Proc (OOP) modes

If you're using OOP modes (State Server or SQL Server), one of


your major cost is the serialization/deserialization of objects in
your session state. ASP.NET performs the
serialization/deserialization of certain "basic" types using an
optimized internal method. "Basic" types include numeric types of
all sizes (e.g. Int, Byte, Decimal, ... etc), String, DateTime,
TimeSpan, Guid, IntPtr and UIntPtr.

If you have a session variable (e.g. an ArrayList object) that is not


one of the "basic" types, ASP.NET will serialize/deserialize it using
the BinaryFormatter, which is relatively slower.

For performance sake it is better to store all session state data


using one of the "basic" types listed above. For example, if you
want to store two things, Name and Address, in session state, you
can either

(a) store them using two String session variables, or


(b) create a class with two String members, and store that class
object in a session
variable. Performance wise, you should go with option (a).

Robustness

• InProc - Session state will be lost if the worker process


(aspnet_wp.exe) recycles, or if the appdomain restarts. It's
because session state is stored in the memory space of an
appdomain. StateServer - Solve the session state loss
problem in InProc mode. Allows a webfarm to store session
on a central server. Single point of failure at the State Server.
26

• SQLServer - Similar to StateServer. Moreover, session state


data can survive a SQL server restart, and you can also take
advantage of SQL server failover cluster.

Caveats

InProc - It won't work in web garden mode, because in that mode


multiple aspnet_wp.exe will be running on the same machine.
Switch to StateServer or SQLServer when using web garden. Also
Session_End event is supported only in InProc mode.

StateServer

• - In a web farm, make sure you have the same


<machineKey> in all your web servers. - Also, make sure
your objects are serializable.
• - For session state to be maintained across different web
servers in the web farm, the Application Path of the website
(For example \LM\W3SVC\2) in the IIS Metabase should be
identical in all the web servers in the web farm.

SQLServer

Q: Why isn't Session_End fired when I call Session_Abandon?


A: First of all, Session_End event is supported only in InProc mode.
In order for Session_End to be fired, your session state has to
exist first. That means you have to store some data in the session
state and has completed at least one request.

Q: Why does the SessionID remain the same after the Session
times out or abandoned?
A:Even though the session state expires after the indicated
timeout period, the session ID lasts as long as the browser
session. What this implies is that the same session ID can
represent multiple sessions over time where the instance of the
browser remain the same.
27

Q: Why does the SessionID changes in every request?


A: This may happen if your application has never stored anything
in the session state. In this case, a new session state (with a new
ID) is created in every request, but is never saved because it
contains nothing.

However, there are two exceptions to this same session ID


behavior:
- If the user has used the same browser instance to request
another page that uses the session state, you will get the same
session ID every time. For details, see "Why does the SessionID
remain the same after the Session times out?"
- If the Session_OnStart event is used, ASP.NET will save the
session state even when it is empty.

Q: What kinds of object can I store in session state?


A: It depends on which mode you are using:
- If you are using InProc mode, objects stored in session state are
actually live objects, and so you can store whatever object you
have created.
- If you are using State Server or SQL Server mode, objects in the
session state will be serialized and deserialized when a request is
processed. So make sure your objects are serializable and their
classes must be marked as so. If not, the session state will not be
saved successfully. In v1, there is a bug which makes the problem
happen unnoticed.

Q: How come Response.Redirect and Server.Transfer is not


working in Session_End?
A: Session_End is fired internally by the server, based on an
internal timer. Thus, there is no HttpRequest associted when that
happens. That is why Response.Redirect or Server.Transferdoes
not make sense and will not work.

Q: Do I have a valid HttpContext in Session_End?


A: No, because this event is not associated with any request.

Q: Will my session state be saved when my page hit an error?


No. Unless you call Server.ClearError in your exception handler.
28

Q: How do I use session state with web services?


A: The extra trick needed is on the caller side. You have to save
and store the cookies used by the web service. See the MSDN
documentation on HttpWebClientProtocol.CookieContainer
property.

However, please note if you're using proxy object to call a web


service from your page, the web service and your page cannot
share the same session state due to architecture limitation.

This can be done if you call your web service through redirect.

Q: I am writing my own HttpHandler. Why is session state not


working?
A: Your HttpHandler has to implement the "marker" interface
IRequiresSessionState or IReadOnlySessionState in order to use
session state.

Q: I am using a webfarm, and I lost session state when directed to


some web servers.
A: For session state to be maintained across different web servers
in the web farm, the Application Path of the website (For example
\LM\W3SVC\2) in the IIS Metabase should be identical in all the
web servers in the web farm.
See KB 325056 for details.

Q: If using "cookieless", how can I redirect from a HTTP page to an


HTTPS page?
A: Try this:
String originalUrl = "/fxtest3/sub/foo2.aspx";
String modifiedUrl = "https://localhost" +
Response.ApplyAppPathModifier(originalUrl);
Response.Redirect(modifiedUrl);
NOTE: Fully qualified URLs in the response.redirect,
server.transfer, and FORM action
tags cannot be used with cookiless sessions

Q: What isn't Session available in my event handler in


global.asax?
29

A: It depends on which event you're handling. Session is available


only after AcquireRequestState event.

Q: Does session state have a locking mechanism that serialize the


access to state?
Session state implements a reader/writer locking mechanism:
- A page (or frame) that has session state write access (e.g. <%@
Page EnableSessionState="True" %>) will hold a writer lock on
the session until the request finishes.
- A page (or frame) that has session state read access (e.g. <%@
Page EnableSessionState="ReadOnly" %>) will hold a reader lock
on the session until the request finishes.
- Reader lock will block a writer lock; Reader lock will NOT block
reader lock; Writer lock will block all reader and writer lock.
- That's why if two frames both have session state write access,
one frame has to wait for the other to finish first

You might also like