ASP.Net Free Short Notes
Unit-I
What
is ASP.Net?
ASP.Net is a web development
platform provided by Microsoft. It is used for creating web-based applications.
ASP.Net was first released in the year 2002.
The first version of ASP.Net
deployed was 1.0. The most recent version of ASP.Net is version 4.6. ASP.Net is
designed to work with the HTTP protocol. This is the standard protocol used
across all web applications.
ASP.Net applications can also be
written in a variety of .Net languages. These include C#, VB.Net, and J#.
The full form of ASP is Active
Server Pages, and .NET is Network Enabled Technologies.
ASP.NET
Architecture and its Components
ASP.Net is a framework which is used
to develop a Web-based application. The basic architecture of the ASP.Net
framework is as shown below.
ASP.NET Architecture Diagram
The
architecture of the.Net framework is based on the following key components
- Language – A variety of languages
exists for .net framework. They are VB.net and C#. These can be used to
develop web applications.
- Library - The .NET Framework includes a
set of standard class libraries. The most common library used for web
applications in .net is the Web library. The web library has all the
necessary components used to develop.Net web-based applications.
- Common Language Runtime - The Common Language
Infrastructure or CLI is a platform. .Net programs are executed on this
platform. The CLR is used for performing key activities. Activities
include Exception handling and Garbage collection.
Below are some of the key
characteristics of the ASP.Net framework
- Code Behind Mode – This is the concept of separation of design and
code. By making this separation, it becomes easier to maintain the ASP.Net
application. The general file type of an ASP.Net file is aspx. Assume we
have a web page called MyPage.aspx. There will be another file called
MyPage.aspx.cs which would denote the code part of the page. So Visual
Studio creates separate files for each web page, one for the design part
and the other for the code.
- State Management – ASP.Net has the facility to control state management.
HTTP is known as a stateless protocol. Let's take an example of a shopping
cart application. Now, when a user decides what he wants to buy from the
site, he will press
the submit button.The application needs to remember the items the user
choose for the purchase. This is known as remembering the state of an application at a
current point in time. HTTP is a stateless protocol. When the user
goes to the purchase page, HTTP will not store the information on the cart
items. Additional coding needs to be done to ensure that the cart items
can be carried forward to the purchase page.
Such an implementation can become
complex at times. But ASP.Net can do state management on your behalf. So
ASP.Net can remember the cart items and pass it over to the purchase page.
- Caching – ASP.Net can implement the
concept of Caching. This improve's the performance of the application. By
caching those pages which are often requested by the user can be stored in
a temporary location. These pages can be retrieved faster and better
responses can be sent to the user. So caching can significantly improve the
performance of an application.
ASP.Net
is a development language used for constructing web-based applications. ASP.Net
is designed to work with the standard HTTP protocol.
Overview of
ASP.NET Controls
The ASP.NET Framework contains more than 90 controls. These controls can be divided into seven groups:
- Standard Controls—Enable you to render standard form elements such as buttons, input fields, and labels.
- Validation Controls—Enable you to validate form data before you submit the data to the server. For example, you can use a RequiredFieldValidator control to check whether a user entered a value for a required input field.
- Rich Controls—Enable you to render things such as calendars, file upload buttons, rotating banner advertisements, and multistep wizards.
- Data Controls—Enable you to work with data such as database data. For example, you can use these controls to submit new records to a database table or display a list of database records.
- Navigation Controls—Enable you to display standard navigation elements such as menus, tree views etc.
- Login Controls—Enables you to display login, change password, and registration forms.
- HTML Controls—Enable you to convert any HTML tag into a server-side control.
Server: Web vs.
Application
Server is a device or a computer program that accepts and responds to the request made by other program, known as client. It is used to manage the network resources and for running the program or software that provides services.
There are two types of servers:
- Web Server
- Application Server
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
EJB is a server-side software component that encapsulates business logic of an application. An EJB web container provides a runtime environment for web related software components, including computer security, Java servlet lifecycle management, transaction processing, and other web services
It is a computer where the web content can be stored. In general web server can be used to host the web sites but there also used some other web servers also such as FTP, email, storage, gaming etc.
Examples of Web Servers are: Apache Tomcat and Resin.
Web Server Working
It can respond to the client request in either of the following two possible ways:
- Generating response by using the script and communicating with database.
- Sending file to the client associated with the requested URL.
The block diagram representation of Web Server is shown below:
Important points
- If the requested web page at the client side is not found, then web server will sends the HTTP response: Error 404 Not found.
- When the web server searching the requested page if requested page is found then it will send to the client with an HTTP response.
- If the client requests some other resources then web server will contact to application server and data is store for constructing the HTTP response.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture.
It provides the middleware services for state maintenance and security, along with persistence and data access. It is a type of server designed to install, operate and host associated services and applications for the IT services, end users and organizations.
The block diagram representation of Application Server is shown below:
The Example of Application Servers are:
- JBoss: Open-source server from JBoss community.
- Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
- Weblogic: Provided by Oracle. It more secured.
- Websphere: Provided by IBM.
Web
Forms
ASP.NET Web Forms is a part of the ASP.NET web application framework and is included with Visual Studio.Web Forms are pages that your users request using their browser. These pages can be written using a combination of HTML, client-script, server controls, and server code.
When users request a page, it is compiled and executed on the server by the framework, and then the framework generates the HTML mark-up that the browser can render. An ASP.NET Web Forms page presents information to the user in any browser or client device.
ASP.NET
and Visual Studio documentation spans several versions. Topics that highlight
features from previous versions may be useful for your current tasks and
scenarios using the latest versions.
ASP.NET Web Forms are:
- Based on Microsoft ASP.NET technology, in which code that runs on the server dynamically generates Web page output to the browser or client device.
- Compatible with any browser or mobile device. An ASP.NET Web page automatically renders the correct browser-compliant HTML for features such as styles, layout, and so on.
- Compatible with any language supported by the .NET common language runtime, such as Microsoft Visual Basic and Microsoft Visual C#.
- Built on the Microsoft .NET Framework. This provides all the benefits of the framework, including a managed environment, type safety, and inheritance.
- Flexible because you can add user-created and third party controls to them.
ASP.NET Web Forms offer:
- Separation of HTML and other UI code from application logic.
- A rich suite of server controls for common tasks, including data access.
- Powerful data binding, with great tool support.
- Support for client-side scripting that executes in the browser.
- Support for a variety of other capabilities, including routing, security, performance, internationalization, testing, debugging, error handling and state management.
Features of ASP.NET Web Forms
- Server Controls- ASP.NET Web server controls are objects on ASP.NET Web pages that run when the page is requested and that render markup to the browser. Many Web server controls are similar to familiar HTML elements, such as buttons and text boxes. Other controls encompass complex behavior, such as a calendar controls, and controls that you can use to connect to data sources and display data.
- Master Pages- ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application.
- Working with Data- ASP.NET provides many options for storing, retrieving, and displaying data. In an ASP.NET Web Forms application, you use data-bound controls to automate the presentation or input of data in web 0page UI elements such as tables and text boxes and drop-down lists.
- Membership- ASP.NET Identity stores your users' credentials in a database created by the application. When your users log in, the application validates their credentials by reading the database. Your project's Account folder contains the files that implement the various parts of membership: registering, logging in, changing a password, and authorizing access.
- Client Script and Client Frameworks- You can enhance the server-based features of ASP.NET by including client-script functionality in ASP.NET Web Form pages. You can use client script to provide a richer, more responsive user interface to users. You can also use client script to make asynchronous calls to the Web server while a page is running in the browser.
- Routing- URL routing allows you to configure an application to accept request URLs that do not map to physical files. A request URL is simply the URL a user enters into their browser to find a page on your web site. You use routing to define URLs that are semantically meaningful to users and that can help with search-engine optimization (SEO).
- State Management- ASP.NET Web Forms includes several options that help you preserve data on both a per-page basis and an application-wide basis.
- Security- An important part of developing a more secure application is to understand the threats to it. Microsoft has developed a way to categorize threats: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege (STRIDE). In ASP.NET Web Forms, you can add extensibility points and configuration options that enable you to customize various security behaviors in ASP.NET Web Forms.
- Performance- Performance can be a key factor in a successful Web site or project. ASP.NET Web Forms allows you to modify performance related to page and server control processing, state management, data access, application configuration and loading, and efficient coding practices.
- Internationalization- ASP.NET Web Forms enables you to create web pages that can obtain content and other data based on the preferred language setting for the browser or based on the user's explicit choice of language. Content and other data is referred to as resources and such data can be stored in resource files or other sources. In an ASP.NET Web Forms page, you configure controls to get their property values from resources. At run time, the resource expressions are replaced by resources from the appropriate localized resource file.
- Debugging and Error Handling- ASP.NET includes features to help you diagnose problems that might arise in your Web Forms application. Debugging and error handling are well supported within ASP.NET Web Forms so that your applications compile and run effectively.
- Deployment and Hosting- Visual Studio, ASP.NET, Azure, and IIS provide tools that help you with the process of deploying and hosting your Web Forms application.
Web Form control
Client side HTML control
: HTML controls are the native
elements of browser. These are client side controls which is accessible
only in the HTML page and not executed in server side. In this senerio user requests the page, receive the page from
the server, then display the HTML and process the Javascript.The client side
validation can be done using the Javascript or vb script. Client side
validation is processed the client side before submitting the form. The
advantage of using the client side validation is it reduces the network trafiic
since the validation is processed in the client machine itself. So
Client side HTML control will improve the performance of the web page.
HTML Server Controls :
when we can add the attribute runat="server" to any HTML control,
such cases it will be an HTML server control. These controls map directly to
html tags and without runat="server" it cannot be accessed from code
behind.
ASP.Net Web Controls: Web
Server Controls or ASP.NET controls Web Server Controls are group of controls
derived directly from the System.Web.UI.WebControls base class. They are
executed on the server side and output HTML sent back to the client browser. If
you use a textbox web control in webform, what happens when the webform runs is
the textbox server control is converted to html control(just like html client
side control). This is extra headache when we can have simple html controls in
hand.So it is better to not use these web controls where performace is an
impotant parameter.
using
System.Web.UI.WebControls;
Because
All Web Forms Controls comes Under this Namespace .
Web Forms Controls:-
There are
some Web Forms Controls which is given below with Real Time Example:-
- Label
Control
- TextBox
control
- Button
control
- Literal
control
- PlaceHolder
control
- HiddenField
control
- FileUpload
control
- Image
control
- ImageButton
control
- ImageMap
control
1.) Label Control:-
The Label Control is basically used
to display the Information(Text) on Web Forms. Any end User can not
Edit(change) the Label Information.
Properties
of Label Control:-
There
are some important properties of Label controls.
- Text:-It
is used to change the Label control information(text).
- Font:-
It is used to sets the font of the Label text.
- ForeColor:-
It is used to sets the text color in the Label.
- Height:-
It is used to Specify the height of the Label Control.
- BackColor
:-It is used to Sets the Background color of the Label control.
- BorderWidth:-It
is used to Sets the Border color of the Label control.
- BorderStyle:-It
is used to Sets the Style of the Label control.
- AccessKey:-It
is used to Navigate the Web Server control.
There
are some steps to implement the Label control on the Web Form
which is given below:
Step
:1
First
Open Your Visual Studio-->File-->New-->Web Site-->Select ASP.NET
Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and
drop Label and Button control from Toolbox on the Web Form as Given
below:
Step :2 Now Double Click on
Click Button and Write the following codes which is shown below:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class labelcontrol : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
}
protected void
Button1_Click(object sender, EventArgs e)
{
Label2.Text =
"You can easily display any information inside it";
}
}
Step :3 Now Run The
Program(Press F5) and Press the Click Button.
Output:
2.) TextBox Control:-
The
TextBox control is used to input the Data(text).Any end user can easily enter
the text in this control.
Properties
of TextBox Control:-
There
are some important properties of TextBox controls.
- Text:-It
is used to sets the text in TextBox Control.
- TextMode:-
It is used to sets the mode of the TextBox Control as Single
Mode,Multiline or Password.
- Rows:-It
is used to sets the number of rows display in a TextBox(Multiline).
- MaxLength:->It
is used to sets the maximum number of character alloweded in a TextBox
control.
- ReadOnly:-It
is used to read the contents by the end used but can not change it.
- Columns:-It
is used to sets the width of character in TextBox.
- AutoCompleteType:-It
is used to sets a value that indicates the Auto Complete behavior of
the TextBox control.
- AutoPostBack:-It
is used to handle the event when the TextBox control lose focus.
- CauseValidation:-It
is used to set a value that validate the TextBox control(client,server).
- TextChange:-It
is an event.It occurs when the end user change the text of the TextBox
control.
·
3.) Button Control:-> The Button control is used to create an Event and
send request to the web server. Properties of Button Control:- There are some
important properties of Button controls.
·
Text:-
It is used to sets the text to be displayed on the Button Control. Click:-It is
an Event that occurs when the Button is clicked.
·
Command:-
It is also an Event that occurs when the Button is clicked.It is used whenever
we are using multiple Button on one page.
·
CommandName:-It
is used to sets the command Name associated with the Button control that is
passed to the command event.
·
OnClientClick:-It
is used to sets the client side script that executes when a Button click event
is fired.
·
CauseValidation:-
It is used to sets the validation that is perform or not when we click the
Button control. There are some steps to implement the TextBox and Button
controls on the Web Form which is given below:
·
Step
:1 First Open Your Visual Studio-->File-->New-->Web Site-->Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on
Web Site-->Add New Item -->Select Web Form--> click Add-->Now drag
and drop TextBox,Label and Button control from Toolbox on the Web Form as Given
below
·
Step
Step :2 Now Double Click on Button Control and Write the following
which is given below:
using System;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public
partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void
Button1_Click(object sender, EventArgs e)
{
String str = TextBox1.Text;
Label2.Text = str;
}
}
Step :3 Now Run The
program(press F5) and click the Button. output:
4.) Literal control:-
It is similar to
Label control but there are some differences and similarities which is given
below.
Literal
and Label control both are used to display the text(information) on the web
form.
On
Browser side Label control is converted to HTML 'Span' tag ‘span’ but Literal
control is not converted in any HTML tag.
We
can provide formatting to the Label control but not to the Literal control.
If
we want to show some HTML code and java script code the we used mainly Literal
control ,not Label control.Encoding Mode is used with Literal control only.
Properties of Literal
Control:-
There are some important properties
of Literal controls.
·
Mode: - IT IS A Literal
control property called Mode which can be changed as Transform,Encode and Pass
Through.
·
Text: - It is used to
sets the caption displayed in the Literal.
There are some steps to
implement the Literal and Label controls on the Web Form which is given below:
Step
:1 First Open Your Visual Studio-->File-->New-->Web Site-- >Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-- >Right Click on
Web Site-->Add New Item -->Select Web Form--> click Add-->Now drag
and drop Literal,Label and Button control from Toolbox on the Web Form as Given below:
Step : 2 Now Double click on
Click button and write the following codes which is given below:
using
System;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public
partial class Literal_and_label_controls_ : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void Button1_Click(object sender,
EventArgs e)
{
Literal1.Text = "Hello Asp.net Website I
am Literal Control";
Label2.Text = "Hello
Asp.net Website I am Label Control";
}
}
Step :3 Now Run
the program(press F5) and press the click button. output:-
Now you see browser source
code,you will see Label control converted to HTML span tag
see it:
5.) PlaceHolder control:-
It
is known as container control in Asp.Net.It is mainly used to store the value
of other controls.You can Add controls to a Web Form by using the
Controls.Add() Method.
There
are some steps to implement the PlaceHolder control on the Web Form which is
given below:
Step :1 First Open Your
Visual Studio-->File-->New-->Web Site-- >Select ASP.NET Empty Web
Site-->OK-->Open Solution Explorer-- >Right Click on Web Site-->Add
New Item -->Select Web Form--> click Add-->Now drag and drop
PlaceHolder and Button control from Toolbox on the Web Form as Given below:
Step :2 Now Double click on
Click button and write the following codes which is given below:
using
System;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public
partial class placeHoldercontrol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void
Button1_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(TextBox1);
}
}
Step :3 Now Run The
Program(Press F5) and Press the Click Button. Output:
6.) HiddenField control:-
It
is used to display the value stored in the HiddenField control in the Label
control.It stores the information in the form of Strings. There are some steps
to implement the HiddenField control on the Web Form which is given below:
Step
:1 First Open Your Visual Studio-->File-->New-->Web Site-- >Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-- >Right Click on
Web Site-->Add New Item -->Select Web Form--> click Add-->Now drag
and drop HiddenField,TextBox,Label and Button control from Toolbox on the Web
Form as Given below:
Step :2 Now
Double click on Click button and write the following codes which is given
below:
using System;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public
partial class HiddenFieldcontrol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
HiddenField1.Value =
TextBox1.Text;
Label2.Text = HiddenField1.Value;
}
}
Step :3 Now Run The
Program(Press F5) and Press the Click Button. Output:
7.
FileUpload Control
It
is basically used to Upload the File on the server using SaveAs() method on the
click Event.When user browse a File and after browse click the Upload button
then File is automatically Upload on the Server.
There
are some steps to implement the FileUpload control on the Web Form which is
given below:
Step
:1 First Open Your Visual Studio-->File-->New-->Web Site-- >Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-- >Right Click on
Web Site-->Add New Item -->Select Web Form--> click Add-->Now drag
and drop FileUpload,Label and Button control from Toolbox on the Web Form as
Given below:
Step :2 Now
Double click on Click button and write the following codes which is given
below:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Fileuploadcontrol :
System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void
Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs("I:/" +
FileUpload1.FileName);
Label2.Text
= "File"+" " + FileUpload1.FileName +" "+"is
uploaded successfully";
}
}
Step :3 Now Run The
Program(Press F5) ,Browse File from your computer and Press the Click Button.
Output:
8.) Image Control:-
It is used to display an image on a web page.
Properties of Image control:-
There are some important properties of Image control
controls.
·
Alternate Text: - It is used to
display alternate text when the image is not present.
·
ImageAlign:- It is used to
sets the alignment of image control on the web page.
·
ImageUrl:- It is used to
sets the path to an image to display in the image control.
·
Font:- It is used to
increase or decrease font of the image control text.
· DescriptionUrl:- It is used to set the location to a detailed description for the image.
There are some steps to
implement the Image control on the Web Form which is given below:
Step :1 First
Open Your Visual Studio-->File-->New-->Web Site-- >Select ASP.NET
Empty Web Site-->OK-->Open Solution Explorer-- >Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and
drop Image control from Toolbox on the Web Form as Given below:
Step :2 Now copy the Image from computer and paste in the Website folder as shown below:
Step
:3 Now Go Image Property-->click on ImageUrl Property-- >select your
image
You
will see following output:
9. ) ImageButton control:-
It is used to display the image on Button instead of
text.Properties of ImageButton is same as Button property.
10.)
ImageMap control:-
It
is used to provide various links(hotspots) to navigate to other web
page,depending on the place where the user clicks.
Properties
of ImageMap Control:-
There are some important
properties of ImageMap control.
Hotspots:- It obtains a
group of Hotspot Object that is defined in a ImageMap.
Target:- It is used to
sets target window to show the web page when the ImageMap control clicked.
Enabled:- It is used to sets a value indicating whether the control can respond to the user interaction.
There
are some steps to implement the Image control on the Web Form which is given
below:
Step
:1 First Open Your Visual Studio-->File-->New-->Web Site-- >Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-- >Right Click on
Web Site-->Add New Item -->Select Web Form--> click Add-->Now drag
and drop ImageMap,ImageButton and Label control from Toolbox on the Web Form as
Given below:
Step
:2 Now copy the Image from computer and paste in the Website folder as shown
below:
Step
:3 Now Go properties of ImageMap and ImageButton and Select appropriate image
by Clicking ImageUrl.
Step
:4 Now go Properties of ImageMap control and select( Collection).Add new
hotspots as shown below:
Step :5 Now Run the Program(Press
F5) and Click the Image Button. output:
Multiple Project Method
If
you separate the Web application into multiple Visual Studio .NET projects, you
may find it easier to manage the development of large Web applications. You can
separate a large development project into smaller projects, which you can
manage and build separately. Your team can work on separate parts of a Web
application by working on separate projects. You should still use source
control software to coordinate work on project files.
Visual Studio .NET does not directly support this method because Visual Studio
.NET Web projects are always created in their own IIS application root
directories with their own assemblies. IIS Web applications cannot span
multiple IIS application root directories.
The advantages of the multiple project method are as follows:
·
It is easier to manage smaller units of a large Web application.
·
You can build each project separately from the other projects,
which shortens the build times during development.
·
You can divide a large Web application into logical units and have
these units share common resources, such as controls.
The
disadvantages of the multiple project method are as follows:
·
Visual Studio .NET does not directly support this method. You must
perform additional steps so that separate Visual Studio .NET projects
participate in the same Web application.
·
Assemblies that access each other's resources must set references
to each other. Visual Studio .NET does not allow circular references.
·
This method is not ideal for small Web applications. For small Web
applications, it is more complex to manage multiple projects than to manage a
single project.
Create the IIS Application
Root Project
To create the
IIS application root project for the Web application, follow these steps:
1.
Start Visual Studio .NET.
2.
On the File menu, point to New,
and then click Project.
3.
In the New Project dialog box, click the language that you
want to use under Project Types, and then
click ASP.NET Web Application under Templates.
4.
In the Location text box, replace the WebApplication# default name with MainWeb. If you are using the local server, you
can leave the server name as http://localhost.
The Location box should then appear as
follows:
http://localhost/MainWeb
Create the Child Projects
To create the
child projects, follow these steps:
1.
For each child project,
right-click the solution in the Solution Explorer window, point to Add, and then click New
Project.
2.
In the Add New Project dialog box, click ASP.NET Web Application under Templates.
3.
In the Location text box, type http://localhost/MainWeb/<subwebname>. This
creates a child project named <subwebname> in a subdirectory of the root
application directory.
4.
Click OK.
5.
Delete any files that are not
needed for a non-application root directory from the project. Specifically,
delete the Global.asax and the Web.config files. This child project will rely
on the Global.asax and the Web.config files from the main project.
6.
If the child project will only
contain shared resources, such as user controls, delete the WebForm1.aspx file.
7.
Build the solution.
Validation
Validations can be performed on
the server side or on the client side ( web browser). The user input validation
take place on the Server Side during a post back session is called Server Side
Validation and the user input validation take place on the Client Side (web
browser) is called Client Side Validation. Client Side Validation does not
require a postback. If the user request requires server resources to validate
the user input, you should use Server Side Validation. If the user request does
not require any server resources to validate the input , you can use Client
Side Validation.
Server
Side Validation
In the
Server Side Validation, the input submitted by the user is being sent to the
server and validated using one of server side scripting languages such as
ASP.Net, PHP etc. After the validation process on the Server Side, the feedback
is sent back to the client by a new dynamically generated web page. It is better
to validate user input on Server Side because you can protect against the
malicious users, who can easily bypass your Client Side scripting language and
submit dangerous input to the server.
Client
Side Validation
In the
Client Side Validation you can provide a better user experience by responding
quickly at the browser level. When you perform a Client Side Validation, all
the user inputs validated in the user's browser itself. Client Side validation
does not require a round trip to the server, so the network traffic which will
help your server perform better. This type of validation is done on the browser
side using script languages such as JavaScript, VBScript or HTML5 attributes.
For
example, if the user enter an invalid email format, you can show an error
message immediately before the user move to the next field, so the user can
correct every field before they submit the form.
Mostly
the Client Side Validation depends on the JavaScript Language, so if users turn
JavaScript off, it can easily bypass and submit dangerous input to the server .
So the Client Side Validation can not protect your application from malicious
attacks on your server resources and databases.
As both
the validation methods have their own significances, it is recommended that the
Server side validation is more SECURE.ASP.NET validation controls validate the
user input data to ensure that useless, unauthenticated, or contradictory data
don't get stored.ASP.NET provides the following validation controls:
- RequiredFieldValidator
- RangeValidator
- CompareValidator
- RegularExpressionValidator
- CustomValidator
- ValidationSummary
BaseValidator
Class
The validation control classes are
inherited from the BaseValidator class hence they inherit its properties and
methods. Therefore, it would help to take a look at the properties and the
methods of this base class, which are common for all the validation controls:
|
Members |
Description |
|
ControlToValidate |
Indicates the input control to
validate. |
|
Display |
Indicates how the error message is
shown. |
|
EnableClientScript |
Indicates whether client side
validation will take. |
|
Enabled |
Enables or disables the validator. |
|
ErrorMessage |
Indicates error string. |
|
Text |
Error text to be shown if
validation fails. |
|
IsValid |
Indicates whether the value of the
control is valid. |
|
SetFocusOnError |
It indicates whether in case of an
invalid control, the focus should switch to the related input control. |
|
ValidationGroup |
The logical group of multiple
validators, where this control belongs. |
|
Validate() |
This method revalidates the
control and updates the IsValid property. |
RequiredFieldValidator
Control
The RequiredFieldValidator control
ensures that the required field is not empty. It is generally tied to a text
box to force input into the text box.
The syntax of the control is as
given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator
Control
The RangeValidator control verifies
that the input value falls within a predetermined range.
It has three specific properties:
|
Properties |
Description |
|
Type |
It defines the type of the data.
The available values are: Currency, Date, Double, Integer, and String. |
|
MinimumValue |
It specifies the minimum value of
the range. |
|
MaximumValue |
It specifies the maximum value of
the range. |
The syntax of the control is as
given:
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter
your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
CompareValidator
Control
The CompareValidator control
compares a value in one control with a fixed value or a value in another
control.
It has the following specific
properties:
|
Properties |
Description |
|
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. |
|
Operator |
It specifies the comparison
operator, the available values are: Equal, NotEqual, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck. |
The basic syntax of the control is
as follows:
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ErrorMessage="CompareValidator">
</asp:CompareValidator>
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.
The following table summarizes the
commonly used syntax constructs for regular expressions:
|
Character
Escapes |
Description |
|
\b |
Matches a backspace. |
|
\t |
Matches a tab. |
|
\r |
Matches a carriage return. |
|
\v |
Matches a vertical tab. |
|
\f |
Matches a form feed. |
|
\n |
Matches a new line. |
|
\ |
Escape character. |
Apart from single character match, a
class of characters could be specified that can be matched, called the
metacharacters.
|
Metacharacters |
Description |
|
. |
Matches any character except \n. |
|
[abcd] |
Matches any character in the set. |
|
[^abcd] |
Excludes any character in the set. |
|
[2-7a-mA-M] |
Matches any character specified in
the range. |
|
\w |
Matches any alphanumeric character
and underscore. |
|
\W |
Matches any non-word character. |
|
\s |
Matches whitespace characters
like, space, tab, new line etc. |
|
\S |
Matches any non-whitespace
character. |
|
\d |
Matches any decimal character. |
|
\D |
Matches any non-decimal character. |
Quantifiers could be added to
specify number of times a character could appear.
|
Quantifier |
Description |
|
* |
Zero or more matches. |
|
+ |
One or more matches. |
|
? |
Zero or one matches. |
|
{N} |
N matches. |
|
{N,} |
N or more matches. |
|
{N,M} |
Between N and M matches. |
The syntax of the control is as
given:
<asp:RegularExpressionValidator ID="string" runat="server"
ErrorMessage="string"
ValidationExpression="string"
ValidationGroup="string">
</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows
writing application specific custom validation routines for both the client
side and the server side 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.
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.
The basic syntax for the control is
as given:
<asp:CustomValidator ID="CustomValidator1"
runat="server"
ClientValidationFunction=.cvf_func.
ErrorMessage="CustomValidator">
</asp:CustomValidator>
Calender
Control
The calendar control is a
functionally rich web control, which provides the following capabilities:
- Displaying one month at a time
- Selecting a day, a week or a
month
- Selecting a range of days
- Moving from month to month
- Controlling the display of the
days programmatically
The basic syntax of a calendar
control is:
<asp:Calender ID = "Calendar1" runat =
"server">
</asp:Calender>
The Calendar control has the
following three most important events that allow the developers to program the
calendar control. They are:
|
Events |
Description |
|
SelectionChanged |
It is raised when a day, a week or
an entire month is selected. |
|
DayRender |
It is raised when each data cell
of the calendar control is rendered. |
|
VisibleMonthChanged |
It is raised when user changes a
month. |
Working
with the Calendar Control
Putting a bare-bone calendar control
without any code behind file provides a workable calendar to a site, which
shows the months and days of the year. It also allows navigation to next and
previous months.
Calendar controls allow the users to
select a single day, a week, or an entire month. This is done by using the
SelectionMode property. This property has the following values:
|
Properties |
Description |
|
Day |
To select a single day. |
|
DayWeek |
To select a single day or an
entire week. |
|
DayWeekMonth |
To select a single day, a week, or
an entire month. |
|
None |
Nothing can be selected. |
The syntax for selecting days:
<asp:Calender ID = "Calendar1" runat =
"server" SelectionMode="DayWeekMonth">
</asp:Calender>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="calendardemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3> Your Birthday:</h3>
<asp:Calendar ID="Calendar1" runat="server SelectionMode="DayWeekMonth" onselectionchanged="Calendar1_SelectionChanged">
</asp:Calendar>
</div>
<p>Todays date is:
<asp:Label ID="lblday" runat="server"></asp:Label>
</p>
<p>Your Birday is:
<asp:Label ID="lblbday" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
The event handler for the event SelectionChanged:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
lblday.Text = Calendar1.TodaysDate.ToShortDateString();
lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}
When the file is run, it should produce the following output:
Ad Rotator Control
AdRotator is a control in ASP.NET that is all about ads
in Web pages. It displays a number of ad images and rotates them or
loads them when a page is refreshed. The ASP.NET AdRotator control
uses an XML file to store the ads and their information. The XML file
must begin and end with an <Advertisements> tag.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />
The
Advertisement File
The advertisement file is an XML
file, which contains the information about the advertisements to be displayed.
It is a text-based markup language that enables you to store data in a structured format by using meaningful tags. The term 'extensible' implies that you can extend your ability to describe a document by defining meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules for creating new markup languages. It is a meta-markup language. It allows developers to create custom tag sets for special uses. It structures, stores, and transports the information.
Following is an example of XML file:
<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK> State Management
State
Management Types
In ASP.NET there are the following 2
State Management methodologies:
Client-Side State Management
Whenever we use Client-Side State
Management, the state related information will directly get stored on the
client-side. That specific information will travel back and communicate with every
request generated by the user then afterwards provides responses after
server-side communication.
This architecture is something like
the following,
Server-Side State Management
Server-Side State Management is
different from Client-Side State Management but the operations and working is
somewhat the same in functionality. In Server-Side State Management all the
information is stored in the user memory. Due to this functionality there is
more secure domains at the server side in comparison to Client-Side State
Management.
The structure is something like the
following,
State
Management Scenario
It will be a little difficult to
directly evaluate what will be better for our application. We cannot directly
say that we will use client-side or server-side architecture of State
Management.
State
Management Techniques
State Management techniques are
based on client side and server side. Their functionality differs depending on
the change in state, so here is the hierarchy:
Client-side | Techniques
Client-Side State Management
techniques are,
- View State
- Hidden field
- Cookies
- Control State
- Query Strings
Server-side | Technique
Server-Side State Management
techniques are,
- Session State
- Application State
Now I am defining each and every
technique in detail with their reference example.
View
State
In general we can say it is used for
storing user data in ASP.NET, sometimes in ASP.NET applications the user wants
to maintain or store their data temporarily after a post-back.. In this case
VIEW STATE is the most used and preferred way of doing that.
This property is enabled by default
but we can make changes depending on our functionality, what we need to do is
just change the EnableViewState value to either TRUE for enabling it or FALSE
for the opposite operation.
Figure: [View State Management]
- // Page Load Event
- protected void Page_Load(object sender, EventArgs e)
- {
- if (IsPostBack)
- {
- if (ViewState["count"] != null)
- {
- int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
- View.Text = ViewstateVal.ToString();
- ViewState["count"]=ViewstateVal.ToString();
- }
- else
- {
- ViewState["count"] = "1";
- }
- }
- }
-
- // Click Event
- protected void Submit(object sender, EventArgs e)
- {
- View.Text=ViewState["count"].ToString();
- }
Points to Remember
Some of the features of view state
are:
- It is page-level State
Management
- Used for holding data
temporarily
- Can store any type of data
- Property dependent
Hidden
Field
A hidden field is used for storing
small amounts of data on the client side. In most simple words it's just a
container of some objects but their result is not rendered on our web browser.
It is invisible in the browser.
It stores a value for the single
variable and it is the preferable way when a variable's value is changed
frequently but we don't need to keep track of that every time in our application
or web program.
Figure: [Hidden Field Management]
- // Hidden Field
-
- int newVal = Convert.ToInt32(HiddenField1.Value) + 1;
- HiddenField1.Value = newVal.ToString();
- Label2.Text = HiddenField1.Value;
Points to Remember
Some features of hidden fields are:
- Contains a small amount of
memory
- Direct functionality access
Cookies
A set of Cookies is a small text
file that is stored in the user's hard drive using the client's browser.
Cookies are just used for the sake of the user's identity matching as it only
stores information such as sessions id's, some frequent navigation or post-back
request objects.
Whenever we get connected to the
internet for accessing a specific service, the cookie file is accessed from our
hard drive via our browser for identifying the user. The cookie access depends
upon the life cycle or expiration of that specific cookie file.
Figure: [Cookie Management]
- int postbacks = 0;
- if (Request.Cookies["number"] != null)
- {
- postbacks = Convert.ToInt32(Request.Cookies["number"].Value) + 1;
- }
- // Generating Response
- else
- {
- postbacks = 1;
- }
- Response.Cookies["number"].Value = postbacks.ToString();
-
- Result.Text = Response.Cookies["number"].Value;
Cookie | Types
Persistent Cookie
Cookies having an expiration date is
called a persistent cookie. This type of cookie reaches their end as their
expiration dates comes to an end. In this cookie we set an expiration date.
- Response.Cookies["UserName"].Value = "Abhishek";
- Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);
-
- HttpCookie aCookie = new HttpCookie("Session");
- aCookie.Value = DateTime.Now.ToString();
- aCookie.Expires = DateTime.Now.AddDays(1);
- Response.Cookies.Add(aCookie);
Non-Persistent Cookie
Non-persistent types of cookies
aren't stored in the client's hard drive permanently. It maintains user
information as long as the user access or uses the services. Its simply the
opposite procedure of a persistent cookie.
- HttpCookie aCookie = new HttpCookie("Session");
- aCookie.Value = DateTime.Now.ToString();
- aCookie.Expires = DateTime.Now.AddDays(1);
- Response.Cookies.Add(aCookie);
Points to Remember
Some features of cookies are:
- Store information temporarily
- It's just a simple small sized
text file
- Can be changed depending on
requirements
- User Preferred
- Requires only a few bytes or
KBs of space for creating cookies
Control
State
Control state is based on the custom
control option. For expected results from CONTROL STATE we need to enable the
property of view state. As I already described you can manually change those
settings.
Points to Remember
Some features of query strings are:
- Used for enabling the View
State Property
- Defines a custom view
- View State property declaration
- Can't be modified
- Accessed directly or disabled
Query
Strings
Query strings are used for some
specific purpose. These in a general case are used for holding some value from
a different page and move these values to the different page. The information
stored in it can be easily navigated to one page to another or to the same page
as well.
Figure: [Query Strings]
- // Getting data
- if (Request.QueryString["number"] != null)
- {
- View.Text = Request.QueryString["number"];
- }
-
- // Setting query string
- int postbacks = 0;
-
- if (Request.QueryString["number"] != null)
- {
- postbacks = Convert.ToInt32(Request.QueryString["number"]) + 1;
- }
- else
- {
- postbacks = 1;
- }
-
- Response.Redirect("default.aspx?number=" + postbacks);
Points to Remember
Some of the features are,
- It is generally used for
holding values
- Works temporarily
- Switches info from one to
another page
- Increase performance
- Uses real and virtual path
values for URL routing
Session State
As we all know, our web
is "Stateless", in other words a new instance of a web
page class, is recreated each time the page is posted to the server. HTTP is a
stateless protocol and it can't hold the client information on the page. For
example, if the user inserts some information on one page and then moves
to the next page then that inserted data will be lost from the first page and
moreover the user will not be able to retrieve that information.
So basically here we need someone to
hold the state of our application. Here is the privitage role of our "session
state". Basically a session is a variable used between the client
and the server that is stored on the server side. Now it can be stored either
on an Internet Information Service (IIS) server that is by default our "inproc"
mode or it can be stored in a state or SQL Server that is our "outproc"
mode. We will discuss both, the inproc and outproc modes in detail later in the
article.
So a session helps to maintain the user state and data all over the application by storing the information on the server memory. Also a session can store any kind of information or object on the server side and is accessible in the entire website.
Every object is stored in the application on the basis of the Key value. We can see both the application and session start up events by adding a "Global.asax" file in our project.
The process of maintaining the
session state proceeds in the following manner. First the client hits
the website and the information is stored in the session. Then a Session
table will be made by default on the IIS server and in the session IDs of all
the users visiting the website will be stored by the server. Now the next time
the client requests some information with the unique session ID from the
server, the server looks in the session providers and retrieves the serialized
data from the state server and type casts the object.
FIG:
PROCESS FOR MAINTAINING THE SESSION STATE IN THE APPLICATION
Now let us see how to store and
retrieve values in a session.
STORING
AND RETRIEVING VALUES FROM SESSION
The following code is used for
storing a value in a session:
- // Storing Username in session.Session[ "UserName" ] = txtUser.Text;
- // Retreiving
- values
- from
- session.// Check whether session variable null
- or not if(Session[ "UserName" ] != null) { // Retreiving UserName
- from
- session lblWelcome.text = "Welcome: +Session[" UserName "];
- }
- else
- {
- //Do something else
- }
As we know all these values will be
stored and retreived from the session on the IIS server by default.
Now for maintaining the load balance
we need to free the IIS server. So we require an "Outproc"
mode of the session state. Now we will study both the "Inproc"
and "Outproc" modes of the session state in detail.
FIG:
INPROC AND OUTPROC MODES IN SESSION STATE AND THEIR RESPECTIVE STATE PROVIDERS
INPROC
SESSION MODE IN SESSION STATE
FIG:
INPROC SESSION MODE
This is the default session mode in
ASP.Net. It stores the information in a memory object in the current
application domain. So it is easily and quickly available and is best suited
for web application performance but the main disadvantage is that because all
the information is stored on the server side in the same application domain, if
we will restart the server all the data will be lost. When the client requests
data, the State Provider reads the data from an in-memory object and return it
to the client. In web.config, we need to specify the session mode and also
set the time out.
Advantages
- It stores session data in a
memory object of the current application domain. So accessing data is very
fast and data is easily available.
- There is not a requirement for
serialization to store the data in InProc session mode.
- Implementation is very easy,
similar to using the ViewState.
Disadvantages
Although an InProc session is the fastest, common and default mechanism, it has
many limitations as in the following:
- If the worker process or
application domain is recycled, all session data will be lost.
- Though it is the fastest, more
session data and more users can affect performance, because of memory
usage.
- We can't use it in Web Garden
scenarios.
- This session mode is not
suitable for web Farm scenarios.
As in the preceding discussion, we
can conclude that InProc is a very fast session storing mechanism but suitable
only for small web applications. InProc session data will be lost if we restart
the server, or if the application domain is recycled. It is also not suitable
for Web Farm and Web Garden scenarios.
Now we will have a look at the other options available to overcome these
problems. First is the StateServer mode.
Application State
Introduction
Application State is a state management technique. Application State is stored
in the memory of the the server and is faster than storing and retrieving
information in a database. Session sate is specific for a single user session,
but Application State is for all users and sessions. Application State does not
have a default expiration period. When we close the worker process the
application object will be lost. Technically the data is shared amongst users
by a HTTPApplcationState class and the data can be stored here in a key/value
pair. It can also be accessed using the application property of the HTTPContext
class.
Application State Life Cycle
Step 1 : When the Browser sends a request to the web server and the
server receives the the request it first checks the extension to determine
whether or not it is ISAPI because this request can only be handled by the
ISAPI extension; if the extension is different then the request is handled by
the server itself.
Step 2 : After receiving the request the Application Manager creates an
application domain. In the application domain an instance of the class
HostingEnvironment is created that provides access to information about all
application resources.
Step 3 : After creating the application domain, ASP.NET initializes the
basic objects as HTTPContext, HTTPRequest and HTTPResponse. HTTPContext holds
objects to the specific application request as HTTPRequest and
HTTPResponse.HTTPRequest contains all the information regarding the current
request like cookies, browser information and so on and the HTTPResponse
contains the response that is sent to the client.
Step 4 : Here all the basic objects are being initialized and the
application is being started with the creation of the HTTPApplication class.
Step 5 : Then events are executed by the HTTPApplication class for any
specific requirement. Here is a list of events:
Global.asax file: the Global.asax file is used for handling application
events or methods. It always exists in the root level. Events are one of the
following of the 2 types in the Global application:
- Events that will be raised on a
certain condition.
- Events that will be raised on
every request.
The application will be started only
once; if 10 users send a request then 10 user sessions are created. The events
of the Global.asax file are:
- Application_Start() : This method is invoked
initially when first application domain is created.
- Session_Start() : This method is called every
time a session is start.
- Application_BeginRequest() : After an application has
started the first method Application_BeginRequest() is executed for every
user.
- Application_AuthenticateRequest()
: It checks to determine whether
or not the user is valid.
- Application_Error() : Whenever an unhandled exception
occurs then this event will be called.
- Session_End() : When a user session is ended
and all the data related to a specific user is cleared then the
Session_End() event is called.
- Application_End() : This method is called before
the application ends. This can take place if IIS is restarted or the
application domain is changing.
- Application_Disposed() : This event is called after the
application will be shut down and the .NET GC is about to reclaim the
memory it occupies. Although this is very late to perform any clean-up but
we can use it for safety purposes.
Sir JAVA programming KE NOTES UPLOAD
ReplyDelete