Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Chapter-8

1. What is ASP.NET? Compare ASP with ASP.NET.


- It is server side technology for developing web application.
- To understand Asp.net first knows ASP and their limitations.
- ASP is purely scripting language and code is not compiled but interpretered. There is
no DLL and EXE generated.
- ASP.NET is not an upgraded version of ASP. It is newly technology.
- It is not compatible with Classic ASP, but ASP.NET may include Classic ASP.

Why ASP.NET better than ASP (Or comparison ASP & ASP.NET)

1. Simple and Easy to develop.


2. Code compiled not interpretered.
3. Better controls than ASP.
4. Controls have events support
5. Better language support
6. Separate Code Behind File
7. Better Authentication and Authorization
8. User accounts & roles
9. Uses ADO.NET not ADO
10. Inbuilt validation controls
11. Debugging Support
12. Easy Configuration
13. Easy deployment

2. ASP.NET Page Life Cycle (Including Events) or Postback


processing Sequence
Page Life Cycle steps:

1. Webpage request comes from browser.


2. IIS received request and Maps the asp.net file extensions (.aspx,.ascx,.asmx,.ashx) to
ASPNET_ISAPI.DLL on Asp.net engine.

6th CE – Dot Net Technology Page 1


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

3. If file name extension has not been mapped to asp.net engine, Asp.net will not
receive request. So IIS handles the request & discard the request without processing.
4. If IIS maps file Extension successfully, it load this ASPNET_ISAPI.DLL and pass request
to it.
5. Now ASPNET_ISAPI.DLL pass this request to ASPNET_WP.EXE Asp.net worker process
and now execution start. Then some page level events begins

Page Level Events

1. Page PreInit
This is event fire before the Page Init.
- Check IsPostback property
- Set Master Page dynamically
- Set Theme property of page dynamically
- Recreate Dynamic controls

2. Init
In this method initialization done for all controls

3. Init Complete
It will fire if all initialization completed.

4. Pre Load
Use this event if you want to process the controls or code before the Page load
events.

5. Load
In this events page calls the OnLoad method of this page and recursively does the
same for each child controls until the page & all controls are loaded.
6. Control Events (Postback)

6th CE – Dot Net Technology Page 2


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- This event handles specific control events such as Button control’s click event or
TextBox’s Textcahnged event. It is also called Postback.
- Each time you click a button, the page is sent back to the server and this process
repeats itself. The action of submitting a page back to the server is called a
Postback.
- At the beginning of every Postback, the Page. Load event fires, which you can
handle to initialize your page.
7. Pre Render
This is the Last event before the HTML Code generated for the page. Use this
events to make final changes.

8. Render
In this method page object call the render methods of each controls that writes
the controls markup and finally sent to the browser.

9. Unload
This event occur for each control and then for the page. Use this event to do final
clean up for specific control such as closing database connection etc..

6. Now if the page level events ends response with above events sends back to the IIS.
7. And Finally IIS sends the response to the client browser.

3. What is validation in web development? Explain various Controls


for validation in APS.NET with Example.
Validation controls are used to:
-Implement presentation logic.
-To validate user input data.
-Data format, data type and data range is used for validation.

Validation is of two types:


- Client Side
- Serve Side

- Client side validation is good but we have to be dependent on browser and scripting
Language support.
- Client side validation is considered convenient for users as they get instant feedback.
The main advantage is that it prevents a page from being Postback to the server
until the client validation is executed successfully.
- For developer point of view serve side is preferable because it will not fail, it is not

6th CE – Dot Net Technology Page 3


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Dependent on browser and scripting language.


- You can use ASP.NET validation, which will ensure client, and server validation. It
work on both end; first it will work on client validation and than on server validation.
- At any cost server validation will work always whether client validation is executed or
not. So you have a safety of validation check.
- For client script .NET used JavaScript. WebUIValidation.js file is used for client
validation by .NET

There are six types of validation controls in ASP.NET

1. RequiredField Validation Control


2. CompareValidator Control
3. RangeValidator Control
4. RegularExpression Validator Control
5. CustomValidator Control
6. ValidationSummary

Validation Control Description


RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the
value of another input control or to a fixed
value
RangeValidator Checks that the user enters a value that falls
between two values
RegularExpressionValidator Ensures that the value of an input control
matches a specified pattern
CustomValidator Allows you to write a method to handle the
validation of the value entered
ValidationSummary Displays a report of all validation errors occurred
in a Web page

Important Common Properties of all validation controls

ControlToValidate The id of the control to validate

Display Legal values are:

- - None (the control is not displayed. Used to show the error


message only in the ValidationSummary control)
- - Static (the control displays an error message if validation fails.
- Space is reserved on the page for the message even if the input
passes validation.

6th CE – Dot Net Technology Page 4


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- - Dynamic (the control displays an error message if validation


fails.
- Space is not reserved on the page for the message if the input
passes validation

EnableClientScript A Boolean value that specifies whether client-side

validation is enabled or not


Enabled A Boolean value that specifies whether the validation control is
enabled or not
ErrorMessage The text to display in the ValidationSummary control when
validation fails.

- This text will also be displayed in the validation control if


the Text property is not set

A Boolean value that indicates whether the control specified by


IsValid
ControlToValidate is determined to be valid
T message to display when validation fails
Text

Examples:

(1) RequiredFieldValidator Control

- The RequiredFieldValidator control ensures that the required field is not empty. If
you want any field compulsory then use this validation control.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"


ControlToValidate="TextBox1" ErrorMessage="First Name Required !">

</asp:RequiredFieldValidator>

- Main Property is ControlToValidate and ErrorMessage

6th CE – Dot Net Technology Page 5


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

(2) RangeValidator Control

- The RangeValidator control verifies that the input value falls within a predetermined
range.
- For example if you want to allow age only 18 to 40 years then Range validator used.
- It has three specific properties:

Properties Description
It defines the type of the data. The available values are: Currency,
Type
Date, Double, Integer, and String.
MinimumValue It specifies the minimum value of the range.
MaximumValue It specifies the maximum value of the range.

<asp:RangeValidator ID="RangeValidator1" runat="server"


ControlToValidate="DropDownList1" ErrorMessage="Only 18 to 40"
MaximumValue="40" MinimumValue="18" Type="Integer">
</asp:RangeValidator>

(3) CompareValidator Control

- The CompareValidator control compares a value of one control with a fixed value or
with a value of another control.
- For Password password and confirm password we can used this validation control.
- It has the following specific properties:

Properties Description

6th CE – Dot Net Technology Page 6


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Type It specifies the data type.


ControlToCompare It specifies the value of the input control to compare with.
ValueToCompare It specifies the constant value to compare with.
It specifies the comparison operator, the available values are:
Operator Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,
LessThanEqual, and DataTypeCheck.

<asp:CompareValidator ID="CompareValidator1" runat="server"


ControlToCompare="TextBox2" ControlToValidate="TextBox3"
ErrorMessage="Password and Confirm Password Must Match!">
</asp:CompareValidator>

(4) RegularExpressionValidator

- The RegularExpressionValidator allows validating the input text by matching against


a pattern of a regular expression.
- The regular expression is set in the ValidationExpression property.
- There are lots of inbuilt regular expressions available in validation expression
property.
- For E-mail Id, URL validation we can used regular expression validation control.
- This is most powerful validation expression.
- For any kind of validation you can search regular expression on internet and you can
used it. We can used more prefer website http://www.regxlib.com/

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox4" ErrorMessage="E-mail id not
valid" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>

(5) CustomValidator

- The CustomValidator control allows writing specific custom validation for both the
client side and the server side validation.
- If your requirement is not fulfill with available inbuilt validation control then with
CustomValidator control you can write custom code and can use for validation.
- The client side validation is accomplished through the ClientValidationFunction
property. The client side validation routine should be written in a scripting
language, such as JavaScript or VBScript, which the browser can understand.

6th CE – Dot Net Technology Page 7


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- The server side validation routine must be called from the control's ServerValidate
event handler. The server side validation routine should be written in any .Net
language, like C# or VB.Net.

<asp:CustomValidator ID="CustomValidator1" runat="server"


ControlToValidate="TextBox5" ErrorMessage="Only 10 characters !"
onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

protected void CustomValidator1_ServerValidate(object source,


ServerValidateEventArgs args)
{
if (args.Value.Length > 10)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

(6) ValidationSummary

- The ValidationSummary control does not perform any validation but shows a
summary of all errors in the page. The summary displays the values of the
ErrorMessage property of all validation controls that failed validation.

Two main properties.

 ShowSummary : shows the error messages in specified format.


 ShowMessageBox : shows the error messages in a separate window.
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" />

4. Explain Configuration File (Web.config and Machine.config) with


different Tags.

Asp.net configuration is stored in two primary XML based files.


(1) Machine.config : (server or machine configuration file)
(2) Web.config : (Application configuration file)

6th CE – Dot Net Technology Page 8


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

1. Machine.config

- Every Asp.net server installation includes a configuration file named Machine.config


and this file is installed as a part of .Net framework installation.
- You can find Machine.config file in, C:\windows\microsoft.net\framework\v2.oxxx
- Machine.config file is used to configure common .net framework setting for all
application on the machine
- It is not a good idea to edit or manipulate the Machine.config file ,If you do not know
what are you doing
- Change to this file can affect all application on your computer
- Because the .net framework supports side by side execution, you find more than one
installation of Machine.config file, if you have installed multiple version of .net.
- Each .net framework installation has its own Machine.config file
- In addition Machine.config file , .net framework install also two more file called
machine.config.default & machine.config.comments
- The machine.config.default file act as backup for Machine.config file
- The machine.config.comments file contains description for all configuration section.

2. Web.config

- Each and every asp.net application has its own configuration settings stored in
web.config file
- The configuration for each web application is unique
- If web application spam’s multiple folders ,each sub folders has its own web.config
file that inherit or overwrites or parents web.config file
- The main diff. between Machine.config & web.config is the file name
- Configuration files divided into multiple sections.
- The root element in xml configuration file is always <configuration>
- Note that the web.config file is case-sensitive, like all XML documents, and starts
every setting with a lowercase letter. This means you cannot write <AppSettings>
instead of <appSettings>.

Advantages of Asp.net configuration file (web.config):

- They are never locked:

You can update web.config settings at any point, even while your application is
running. If there are any requests currently under way, they’ll continue to use the
old settings, while new requests will get the changed settings right away.

6th CE – Dot Net Technology Page 9


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- They are easily accessed and replicated:

with appropriate network rights, you can change a web.config file from a remote
computer. You can also copy the web.config file and use it to apply identical settings
to another application or another web server that runs the same application in a
web farm scenario.

- The settings are easy to edit and understand:

The settings in the web.config file are human readable, which means they can be
edited and understood without needing a special configuration tool.

Common Configuration Settings (For Web.config)

1. Connection String:

- The <connectionStrings> section allows you to define the connection information for
accessing a database.
- Connection string information stored either <appSettings/> or
<connectionStrings/> section.
- In asp.net 1.1 all the connection string info was stored in <app setting> section
- Examples , how to store connection string

- Using <app setting>

<configuration>
<appSettings>
<add key="constr" value="datasource=sqlexpress; initial
catalog=test; Integrated security=true"/>
</appSettings>
</configuration>

- Now access it in your application like:

SqlConnection con=New
SqlConnection(ConfigurationSettings.AppSettings["constr"])

- Using <ConnectionStrings>:

<configuration>
<connectionStrings>
<add name="constr" connectionString="datasource=sqlexpress;
initial catalog=test; Integrated security=true"/>

6th CE – Dot Net Technology Page 10


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

</connectionStrings>
</configuration>

- Now access it in your application like:

SqlConnection con = New


SqlConnection(ConfigurationManager.ConnectionStrings["constr"]
.ConnectionString)

2. Compilation Settings

<compilation tempDirectory="" debug="true" batch="true"


maxBatchSize="" defaultLanguage="" >
</compilation>

- tempDirectory specifies the directory to use for temporary file storage during
compilation
- You can set compilation debug=true to insert debugging symbols into the compiled
page. And default is False
- Batch specifies whether batch compilation is support or not. And default is True
- maxBatchSize specifies the maximum no. of pages per batched compilation and
default value is 1000
- defaultLanguage specifies the default programming language such as VB or C# to use
in dynamic compilation files. And default is VB.

3. Page Settings

- With this setting we can set the general settings of a page like viewstate, MasterPageFile
and Themes.

<pages enableViewState ="true" masterPageFile="Master1.master"


theme="summer" styleSheetTheme="" >

</pages>

- By using the MasterPageFile and theme attributes, we can specify the master page
and theme for the pages in web application.
- Also we can enable or disable viewstate for particular page.

4. Custom Error Settings

6th CE – Dot Net Technology Page 11


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- In asp.net when error is occur then asp.net display the error page with source code and
line number of the error.
- Now if source code and error messages are displayed, it is possible to hack your site
code by hackers.
- So to overcome this problem asp.net provides excellent custom error mechanism.
- The <customErrors> section enables configuration of what to do if/when an unhandled
error occurs during the execution of a request. Specifically,it enables developers to
configure html error pages to be displayed in place of a error.

<customErrors mode="RemoteOnly" defaultRedirect="welcome.html">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

- In this example if error occurs, welcome.html page will be display instead of error.

5. Location Settings

- If you are working with a major project, you have numbers of folders and sub-folders, at
this kind of particular situation, you can have two options to work with.
- First thing is to have a Web.config file for each and every folder(s) and Sub-folder(s).
- And the second one is to have a single Web.config for your entire application.
- If you use the first approach, then you might be in a smoother way.
- But what if you have a single Web.config and you need to configure the sub-folder or
other folder of your application.
- The right solution is to use the "Location" tag of Web.config file.

<location path="Admin">
<system.web>
<pages theme="summer"></pages>
</system.web>
</location>

- Here for Admin pages you can set theme=suumer.

6. Session State Settings

- As we all know, the ASP.NET is stateless and to maintain the state we need to use the
available state management techniques of ASP.NET.
- You can configure state management in web.config file with <sessionState> tag.
- For details see chapter-11 state management.

<sessionState mode="InProc" cookieless="true">


6th CE – Dot Net Technology Page 12
ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

</sessionState>

7. Authentication Settings

- Authentication is the process that determines the identity of users.


- Authentication works in conjunction with authorization.
- After a user has been authenticated, a developer can determine if the identified user has
valid authorization to proceed.
- It is impossible to give <authorization> if no <authentication> has been applied.
- You can use <authentication> mode as shown below.

<configuration>
<system.web>
<authentication mode="[Windows/Forms/Passport/None]">
</authentication>
</system.web>
</configuration>

- You can use authentication mode like windows, Forms, Passport and None

8. Authorization Settings

- <authorization> tag has list of access rules that either allow or deny a particular users.
- We can use <allow> or <deny> tag to create or modify access rules.
- Astrisk(*) means “All Users”
- Question Mark means “All Anonymous users”
- We can use <authorization> section like this:

<authorization>
<allow users="*"/>
<deny users="?"/>
<allow users="ark"/>

<allow roles="admin"/>
<deny roles="member"/>
</authorization>

Windows Authentication

- This is the default authentication mode in ASP.NET.

6th CE – Dot Net Technology Page 13


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Windows based authentication is handled between the windows server where the
Asp.net application resides and the client machine.
- In windows based authentication, request goes directly to IIS to provide basic
authentication process.
- This type of authentication is quite useful in an intranet environment.
- To work with windows based authentication you have to create users & groups.
- You can assign windows authentication like,

<authentication mode="Windows"/>
<authorization>
<allow users ="*" />
</authorization>

Forms Authentication

- Forms authentication allows you to use custom login page with your own code. So end
user can simply enters his username & password into HTML form.
- This authentication mode is based on cookies where the user name and the password are stored
either in a text file or the database.
- After a user is authenticated, the user’s credentials are stored in a cookie for use in that session.
- When the user has not logged in and requests for a page that is insecure, he or she is redirected
to the login page of the application.
- Forms authentication supports both session and persistent cookies.
<configuration>
<system.web>
<authentication mode="Forms"/>
<forms name="login" loginUrl="login.aspx" />
<authorization>
<deny users="?"/>
</authorization>

</system.web>
</configuration>

- Here name is the name of cookie saved use to remember the user from request to
request.
- LoginUrl specifies the URL to which the request is redirected for login if no valid
authentication cookie is found.

Passport Authentication

6th CE – Dot Net Technology Page 14


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

- Passport authentication is works with Microsoft passport identity system.


- So, if a user has passport account they can login to your site and other passport oriented
sites.
- When your application is enable for passport authentication, the request is actually
redirected to the Microsoft passport site where the user can enter his credentials.
- If the authentication is successful, request is redirected back to your application.
- Very few internet sites uses Microsoft passport authentication services.

9. httpRuntime settings

<httpRuntime enable="true" maxRequestLength="" executionTimeout=""/>

- Enable attributes specifies whether the current Asp.net application is enabled or


disabled.
- maxRequestLength specifies the maximum size of file uploaded accepted by asp.net
runtime. Default is 4096 kb (4 MB). If the Asp.net application require huge files to
upload, it is better to change this setting.
- executionTimeout specifies the timeout option for asp.net request. Default value is “90”
seconds. If you have a asp.net webpage that takes longer than 90 seconds to execute
you can extend the time limit in the configuration.

5. Explain Rich Server Controls


- Rich Controls are: (1)AdRotator (2)Calendar

(1) AdRotator

- Mainly used for advertisement to post various Advertise on website.


- The basic purpose of the AdRotator is to provide a graphic on a page that is chosen
randomly from a group of possible images.
- In other words, every time the page is requested, an image is selected randomly and
displayed.
- The AdRotator stores its list of image files in an XML file. This file uses the format
shown here
- Create XML file in solution explorer like below
<Advertisements>

6th CE – Dot Net Technology Page 15


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

<Ad>
<ImageUrl>Sunset.jpg</ImageUrl>
<NavigateUrl>http://www.kirc.ac.in </NavigateUrl>
<AlternateText>Sunset image</AlternateText>
<Impressions>1</Impressions>
<Keyword>Computer</Keyword>
</Ad>
</Advertisements>

- This example shows a single possible advertisement. To add more advertisements, you
can create multiple <Ad> elements and place them all inside the root <Advertisements>
element.
- After the creating XML file bind it with AdvertisementFile Property of AdRotator control.
Advertisement File Elements:

(2) Calendar

- The Calendar control presents a calendar that you can place in any web page.
- The Calendar control presents a single-month view, as shown in following Figure.

- The user can navigate from month to month using the navigational arrows.
- You can access a date which is selected by user at run time through code.

6th CE – Dot Net Technology Page 16


ADITYA SILVER OAK INSTITUTE OF TECHNOLOGY (CE/IT DEPARTMENT)

Protected Sub Calendar1_SelectionChanged()Handles


Calendar1.SelectionChanged

TextBox1.Text = Calendar1.SelectedDate.ToString();

End Sub

- With this code once you select a date that date should be display in TextBox1
- Calendar control has lots of property try it practically.

Note: Here I explain only Rich server controls. See all common control’s property and try
it practically. Also remember all the important property of each server control.

6th CE – Dot Net Technology Page 17

You might also like