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

Syllabus 2

Visual Studio_CSS 7
Life Cycle 19
Introduction 29
First Example 55
Environment 77
ASP.NET Web Forms Server Controls 96
ASP.NET Models 131
ASP.NET Event Handling 138
Mod2-Validation Controls 150
Intro. to Validation controls 186
StateManagement-Part1 205
StateManagement-Part2 214
StateManagement-Part3 251
validation 282
ADO.Net 286
Data Source Controls and Data Controls 319
DataListView controls 352
Membership 376
Login Controls 407
Visual Programming
BCA S5
Syllabus
▪ An Introduction to ASP.NET web
programming – An introduction to
web programming, an introduction
to ASP.NET application development,
quick preview of how an ASP.NET
application works.
▪ Visual Studio features for working
Module 1 with CSS.
▪ Introduction to server controls, how
to work with button controls, text
boxes, labels, check boxes, radio
button, list controls, and other web
server controls like image, hyperlink,
file upload, and calendar controls.
▪Introduction to validation
controls, basic validation
controls, validation techniques
and advanced validation
controls.
Module 2 ▪How to manage state – how to
use view state, session state
and application state.
▪How to use cookies.
▪An introduction to database
programming – Introduction to
relational database, how to use
SQL to work with data in
database.
▪Introduction to ADO.NET 4.
Module 3 How to use SQL data source,
how to use custom statements
and stored procedures, Data list
controls, Data binding,
advanced features of a SQL data
source.
▪ Customise the GridView control,
Update GridView data, DataListView
controls, FormView Control, ListView
control and update ListView data.
▪ Introduction to SSL, how to get and
use digital source certificate, how to
Module 4
use a secure connection, Introduction
to authentication, how to setup
authentication and authorization,
how to use login controls, how to
configure ASP.NET application, how
to deploy an ASP.NET application.
ASP.NET PROGRAMMING

Module 1
WHAT IS CSS?
Cascading Style Sheet
Stylesheet Language
Standards-based set of properties and attributes to define
styles
To describe the presentation a document written in a
‘markup language’ like HTML or XML
Markup encoding: <p>My paragraph here.</p>
Defines the style of how things in <p> tags appear.
Font, color, size, margins, etc.
Cascading
Rules to determine how to apply markup that contains other
markup
CONTINUE….
Separate Content from Form
⚫ Content is the text and images, marked up to define regions of
specific types
⚫ Form defines the “style” for the content
<font size=“14px”>
My First Header
</font>
<font size=“12px” color=“red” face=“Verdana”>
The old My information 1 goes here.
</font>
way: <font size=“14px”>
My Second Header
</font>
<font size=“12px” color=“red” face=“Verdana”>
Different information goes here.
</font>
CONTINUE….
Separate Content from Form
⚫ Content
<p class=“header”>My First Header</p>
<p class=“info”>My Information 1 goes here</p>
<p class=“header”>My Second Header</p>
<p class=“info”>Different Information goes here</p>
(Specific markup properties like Class will be discussed later).

⚫ Form or Style

.header { font-size:14px;}
.info { font-family: verdana;
font-color: blue;
font-size: 12px; }
CONTINUE….
Separate Content from Form
⚫ Specify the style once for every instance of that
class.
Example: Specify the font once for all text on the
HTML page that you’ve identified as a “header”.

⚫ The style sheet can be a separate file which all


HTML pages on your entire site can link to.
Only have to specify the style once for your
ENITRE SITE

⚫ Can change the style for your entire site by editing


only ONE FILE.
CSS SKINNING
“Skinning” - changing the look of a page or your site
⚫ Selecting an appearance by choosing which stylesheet to use.

<link rel="stylesheet" type="text/css" href=“skin1.css" />

<p class=“info”>My Information 1 goes here</p>

skin1.css
.info { background-color: White;
font-family: Verdana;
font-color: Blue; }

Some information goes here.


CONTINUE….
“Skinning” - changing the look of a page or your site
⚫ Selecting an appearance by choosing which stylesheet to use.

<link rel="stylesheet" type="text/css" href=“skin2.css" />

<p class=“info”>My Information 1 goes here</p>

skin2.css
.info { background-color: Blue;
font-family: Serif;
font-color: White; }

Some information goes here.


CSS SYNTAX
3 Elements to a CSS Statement
⚫ Selector
What HTML sections does it affect?
⚫ Property
What attribute of that HTML section will be affected?
⚫ Value
What change will be made to that attribute?
THREE CSS DEFINITION LOCATIONS
Inline: the “style” attribute
<p style=“font-color:red;font-size:10px;”>Content</p>
Note, the selector for inline CSS is the tag which contains the style attribute.
Internal: the <style> markup tag
<html><head><style>
p { background-color: Red;
font-family: serif;
font-color: White; }
</style></head><body>
<p>Content</p>
</body></html>
External: the .css stylesheet file
<link rel="stylesheet" type="text/css" href=“mystylesheet.css" />
CSS SYNTAX: SELECTORS
There are many kinds of selectors and many ways to reference them:
⚫ Type, Class, ID, Pseudo, etc.

HTML Type Tag – selected with the tag type


p { font-size: 10px;
font-color: White; }

<p>Content</p>

The Class Attribute – precede the class with a period


.myinfo { font-size: 10px;
font-color: White; }
.myinfo1 {font-size: 10px;
font-color: blue;
background-color:green; }

<p class=“myinfo”>Content</p>
<div class=“myinfo1”>Other content</div>
CASCADING INHERITANCE
Nested elements inherit
the properties from the
its parent

If you specify a style for the body { font-family: Verdana;


<body> tag it will affect all font-size: 14px; }
content in your HTML page.
body { font-family: Verdana;
font-size: 1.1em; }
If you want to override .littletext { font-size: 8px; }
inherited settings, you
<body>
need to specify a style in This text is larger.
a more local element <p class=“littletext”>This text is
smaller.</p>
PROS & CONS
Pros
⚫ Greater designer control of the appearance of the
page
⚫ Easier management of site-wide changes
⚫ Greater accessibility to web sites by non-graphical
browsers and web-page-reading software

Cons
⚫ Different browsers may interpret Style Sheets in
different ways
⚫ Some styles may not be seen at all on some
browsers
ASP.NET
Module I
ASP.NET Life Cycle
ASP.NET life cycle specifies, how:
• ASP.NET processes pages to produce dynamic
output
• The application and its pages are instantiated
and processed
• ASP.NET compiles the pages dynamically
The ASP.NET life cycle could be divided into two
groups:
• Application Life Cycle
• Page Life Cycle
ASP.NET Application Life
Cycle
The application life cycle has the following stages:
• User makes a request for accessing application
resource, a page. Browser sends this request to the
web server.
• A unified pipeline receives the first request and the
following events take place:
• An object of the class ApplicationManager is
created.
• An object of the class HostingEnvironment is
created to provide information regarding the
resources.
• Top level items in the application are compiled.
Continue….
• Response objects are created. The application
objects such as HttpContext, HttpRequest and
HttpResponse are created and initialized.
• An instance of the HttpApplication object is
created and assigned to the request.
• The request is processed by the HttpApplication
class. Different events are raised by this class for
processing the request.
ASP.NET Page Lifecycle
• In ASP.NET, a web page has execution lifecycle that
includes various phases. These phases include
initialization, instantiation, restoring and
maintaining state etc. it is required to understand
the page lifecycle so that we can put custom code
at any stage to perform our business logic.
Page Lifecycle stages
The following table contains the lifecycle stages of
ASP.NET web page.
Stage Description
Page request This stage occurs before the lifecycle begins.
When a page is requested by the user,
ASP.NET parses and compiles that page.
Start In this stage, page properties such as Request
and response are set. It also determines the
Request type.
Initialization In this stage, each control's UniqueID property
is set. Master page is applied to the page.

Load During this phase, if page request is postback,


control properties are loaded with information.
Continue….
Postback event handling In this stage, event handler is called if
page request is postback. After that,
the Validate method of all validator
controls is called.

Rendering Before rendering, view state is saved


for the page and all controls. During the
rendering stage, the page calls the
Render method for each control,
providing a text writer that writes its
output to the OutputStream object of
the page's Response property.

Unload At this stage the requested page has


been fully rendered and is ready to
terminate.at this stage all properties are
unloaded and cleanup is performed.
Continue….
• A requested page first loaded into the server
memory after that processes and sent to the
bowser. At last it is unloaded from the server
memory. ASP.NET provides methods and events at
each stage of the page lifecycle that we can use in
our application. In the following table, we are
tabled events.
ASP.NET Life Cycle Events
Page Event Typical Use
PreInit This event is raised after the start stage is
complete and before the initialization stage.
Init This event occurs after all controls have been
initialized. We can use this event to read or
initialize control properties.
InitComplete This event occurs at the end of the page's
initialization stage.We can use this event to
make changes to view state that we want to
make sure are persisted after the next
postback.
PreLoad This event is occurs before the post back data
is loaded in the controls.
Load This event is raised for the page first time and
then recursively for all child controls.
Control This event is used to handle specific control
events events such as Button control' Click event.
Continue….
LoadComplete This event occurs at the end of the
event-handling stage. We can use this
event for tasks that require all other
controls on the page be loaded.
PreRender This event occurs after the page object has
created all controls that are required in
order to render the page.
PreRenderComplete This event occurs after each data bound
control whose DataSourceID property is set
calls its DataBind method.
SaveStateComplete It is raised after view state and control
state have been saved for the page and for
all controls.
Render This is not an event; instead, at this stage
of processing, the Page object calls this
method on each control.
Unload This event raised for each control and then
for the page.
ASP.NET
Module I
Introduction to .NET
Framework
• .NET is a software framework which is designed
and developed by Microsoft. The first version of
.Net framework was 1.0 which came in the year
2002. In easy words, it is a virtual machine for
compiling and executing programs written in
different languages like C#, VB.Net etc.
• It is used to develop Form-based applications,
Web-based applications, and Web services. There is
a variety of programming languages available on
the .Net platform, VB.Net and C# being the most
common ones are .
Continue….
• It is used to build applications for Windows, phone,
web etc. It provides a lot of functionalities and also
supports industry standards.

• .NET Framework supports more than 60


programming languages in which 11 programming
languages are designed and developed by
Microsoft. The remaining Non-Microsoft
Languages which are supported by .NET
Framework but not designed and developed by
Microsoft.
Continue….
11 Programming Languages which are designed and
developed by Microsoft are:
• C#.NET
• VB.NET
• C++.NET
• J#.NET
• F#.NET
• JSCRIPT.NET
• WINDOWS POWERSHELL
• IRON RUBY
• IRON PYTHON
• C OMEGA
• ASML(Abstract State Machine Language)
Main Components of .NET Framework
Common Language Runtime (CLR)
• CLR is the basic and Virtual Machine component of
the .NET Framework.
• It is the run-time environment in the .NET Framework
that runs the codes and helps in making the
development process easier by providing the various
services such as remoting, thread management,
type-safety, memory management, robustness etc.
• Basically, it is responsible for managing the execution
of .NET programs regardless of any .NET programming
language.
• It also helps in the management of code, as code that
targets the runtime is known as the Managed Code and
code doesn’t target to runtime is known as
Unmanaged code.
Continue….
Main components of CLR
• Common Language Specification (CLS)
• Common Type System (CTS)
• Garbage Collection (GC)
• Just In – Time Compiler (JIT)
Continue….
Common Language Specification (CLS)
• It is responsible for converting the different .NET
programming language syntactical rules and
regulations into CLR understandable format.
Basically, it provides the Language Interoperability.
Language Interoperability means to provide the
execution support to other programming languages
also in .NET framework.
Continue….
Language Interoperability can be achieved in two ways:
• Managed Code: The MSIL(Microsoft Intermediate
Language) code which is managed by the CLR is known
as the Managed Code. For managed code CLR
provides three .NET facilities:
• CAS(Code Access Security)
• Exception Handling
• Automatic Memory Management.
• Unmanaged Code: Before .NET development the
programming language like .COM Components &
Win32 API do not generate the MSIL code. So these are
not managed by CLR rather managed by Operating
System which is called unmanaged code.
Continue….
Common Type System (CTS)
• Every programming language has its own data type
system, so CTS is responsible for the understanding
all the data type system of .NET programming
languages and converting them into CLR
understandable format which will be a common
format.
Continue….
• There are 2 Types of CTS that every .NET
programming language have :
• Value Types: Value Types will directly store the
value directly into the memory location. These types
work with stack mechanism only. CLR allots memory
for these at Compile Time.
• Reference Types: Reference Types will contain a
memory address of value because the reference
types won’t store the variable value directly in
memory. These types work with Heap mechanism.
CLR allots memory for these at Runtime.
Continue….
Garbage Collector
• It is used to provide the Automatic Memory
Management feature. Suppose if there is no
garbage collector then programmers have to write
the memory management codes which will be a
kind of overhead on programmers.
Continue….
JIT(Just In Time Compiler)
• It is responsible for converting the CIL(Common
Intermediate Language) into machine code or
native code using the Common Language Runtime
environment.
Continue….
Framework Class Library (FCL)
• It is the collection of reusable, object-oriented
class libraries and methods etc. that can be
integrated with CLR. Also called the Assemblies. It
is just like the header files in C/C++ and packages in
the java. Installing .NET framework basically is the
installation of CLR and FCL into the system.
Server-side Programming
• It is the program that runs on server dealing with the
generation of content of web page.

1) Querying the database


2) Operations over databases
3) Access/Write a file on server.
4) Interact with other servers.
5) Structure web applications.
6) Process user input.

• For example if user input is a text in search box, run a


search algorithm on data stored on server and send the
results.
Continue….
The Programming languages for server-side
programming are :

1) PHP
2) C++
3) Java and JSP
4) Python
5) Ruby on Rails
Client-side Programming
• It is the program that runs on the client machine
(browser) and deals with the user interface/display
and any other processing that can happen on client
machine like reading/writing cookies.
1) Interact with temporary storage
2) Make interactive web pages
3) Interact with local storage
4) Sending request for data to server
5) Send request to server
6) work as an interface between server and user
Continue….
The Programming languages for client-side
programming are :

1) JavaScript
2) VBScript
3) HTML
4) CSS
5) AJAX
Continue….
Introduction to ASP.NET
• ASP.NET is a web development platform, which
provides a programming model, a comprehensive
software infrastructure and various services required
to build up robust web applications for PC, as well as
mobile devices.
• ASP.NET works on top of the HTTP protocol, and uses
the HTTP commands and policies to set a
browser-to-server bilateral communication and
cooperation.
• ASP.NET is a part of Microsoft .Net platform. ASP.NET
applications are compiled codes, written using the
extensible and reusable components or objects
present in .Net framework. These codes can use the
entire hierarchy of classes in .Net framework.
Continue….
• The ASP.NET application codes can be written in
any of the following languages:
• C#
• Visual Basic.Net
• Jscript
• J#
• ASP.NET is used to produce interactive, data-driven
web applications over the internet. It consists of a
large number of controls such as text boxes,
buttons, and labels for assembling, configuring,
and manipulating code to create HTML pages.
Continue….
• It is used to develop websites, web applications
and web services. It provides fantastic integration
of HTML, CSS and JavaScript. It was first released in
January 2002. It is built on the Common Language
Runtime (CLR) and allows programmers to write
code using any supported .NET language.
• ASP.NET provides three development styles for
creating web applications:
• Web Forms
• ASP.NET MVC
• ASP.NET Web Pages
Continue….
Web Forms
• It is an event driven development framework. It is used
to develop application with powerful data access. It
provides server side controls and events to create web
application. It is part of the ASP.NET framework.
ASP.NET MVC
• It gives us a MVC (Model View Controller),
patterns-based way to build dynamic websites. It
enables a clean separation of concerns and that gives
you full control over markup for enjoyable, agile
development. It also provides many features that
enable fast development for creating outstanding
applications.
Continue….
ASP.NET Web Pages
• It is used to create dynamic web pages. It provides
fast and lightweight way to combine server code
with HTML. It helps to add video, link to the social
sites. It also provides other features like you can
create beautiful sites that conform to the latest
web standards.
Continue….
ASP.NET PROGRAMMING
Module I
Introduction
⚫ An ASP.NET page is made up of a number of server
controls along with HTML controls, text, and images.
Sensitive data from the page and the states of different
controls on the page are stored in hidden fields that
form the context of that page request.
⚫ An ASP.NET page is also a server side file saved with
the .aspx extension. It is modular in nature and can be
divided into the following core sections:
⚫ Page Directives
⚫ Code Section
⚫ Page Layout
Page Directives
⚫ The page directives set up the environment for the
page to run. The @Page directive defines
page-specific attributes used by ASP.NET page
parser and compiler. Page directives specify how
the page should be processed, and which
assumptions need to be taken about the page.
⚫ It allows importing namespaces, loading
assemblies, and registering new controls with
custom tag names and namespace prefixes.
Code Section
⚫ The code section provides the handlers for the page
and control events along with other functions
required. We mentioned that, ASP.NET follows an
object model. Now, these objects raise events when
some events take place on the user interface, like a user
clicks a button or moves the cursor. The kind of
response these events need to reciprocate is coded in
the event handler functions. The event handlers are
nothing but functions bound to the controls.
⚫ The code section or the code behind file provides all
these event handler routines, and other functions used
by the developer. The page code could be precompiled
and deployed in the form of a binary assembly.
Page Layout
⚫ The page layout provides the interface of the page. It
contains the server controls, text, inline JavaScript, and
HTML tags.
⚫ The following code snippet provides a sample
ASP.NET page explaining Page directives, code section
and page layout written in C#:
Example
<!-- directives -->
<% @Page Language="C#" %>

<!-- code section -->


<script runat="server">

private void convertoupper(object sender, EventArgs e)


{
string str = mytext.Value;
changed_text.InnerHtml = str.ToUpper();
}
</script>
Continue….
<!-- Layout -->
<html><head><title> Change to Upper Case
</title></head>
<body>
<h3> Conversion to Upper Case </h3>
<form runat="server">
<input runat="server" id="mytext" type="text" />
<input runat="server" id="button1" type="submit"
value="Enter..." OnServerClick="convertoupper"/><hr />
<h3> Results: </h3>
<span runat="server" id="changed_text" />
</form></body></html>
Using Visual Studio IDE
⚫ Let us develop the same example using Visual Studio
IDE. Instead of typing the code, you can just drag the
controls into the design view:
Continue….
⚫ The content file is automatically developed. All you
need to add is the Button1_Click routine, which is as
follows:
protected void Button1_Click(object sender,
EventArgs e)
{
string buf = TextBox1.Text;
changed_text.InnerHtml = buf.ToUpper();
}
Continue….
⚫ The content file code is as given:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="firstexample._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitiona
l.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title></head>
Continue….
<body><form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"
style="width:224px"></asp:TextBox>
<br /><br />
<asp:Button ID="Button1" runat="server" Text="Enter..."
style="width:85px" onclick="Button1_Click" />
<hr /><h3> Results: </h3>
<span runat="server" id="changed_text"
/></div></form>
</body></html>
Continue….
⚫ Execute the example by right clicking on the design
view and choosing 'View in Browser' from the popup
menu. This generates the following result:
ASP.NET
Module I
ASP.NET - Environment Setup

◼ The key development tool for building


ASP.NET applications and front ends is Visual
Studio.
◼ Visual Studio is an integrated development
environment for writing, compiling, and
debugging the code. It provides a complete
set of development tools for building
ASP.NET web applications, web services,
desktop applications, and mobile
applications.
Installation

◼ Step 1 − Once downloading is complete, run


the installer. The following dialog will be
displayed.
Continue….

◼ Step 2 − Click on the Install button and it will


start the installation process.
Continue….

◼ Step 3 − Once the installation process is


completed successfully, you will see the
following dialog. Close this dialog and restart
your computer if required.
Continue….

◼ Step 4 − Open Visual Studio from start Menu


which will open the following dialog. It will be
a while for the first time for preparation.
Continue….
◼ Step 5 − Once all is done you will see the main
window of Visual studio.
Continue….

◼ Let’s create a new project from


File → New → Project
The Visual Studio IDE
◼ The new project window allows choosing an
application template from the available
templates.
Continue….
◼ When you start a new web site, ASP.NET
provides the starting folders and files for the
site, including two files for the first web form of
the site.
◼ The file named Default.aspx contains the HTML
and asp code that defines the form, and the file
named Default.aspx.cs (for C# coding) or the
file named Default.aspx.vb (for VB coding)
contains the code in the language you have
chosen and this code is responsible for the
actions performed on a form.
Continue….

◼ The primary window in the Visual Studio IDE


is the Web Forms Designer window. Other
supporting windows are the Toolbox, the
Solution Explorer, and the Properties
window. You use the designer to design a web
form, to add code to the control on the form
so that the form works according to your
need, you use the code editor.
Working with Views and Windows
◼ You can work with windows in the following
ways:
◼ To change the Web Forms Designer from one
view to another, click on the Design or source
button.
◼ To close a window, click on the close button on
the upper right corner and to redisplay, select it
from the View menu.
◼ To hide a window, click on its Auto Hide button.
The window then changes into a tab. To display
again, click the Auto Hide button again.
◼ To change the size of a window, just drag it.
Continue….
Adding Folders and Files to your
Website
◼ When a new web form is created, Visual Studio
automatically generates the starting HTML for
the form and displays it in Source view of the web
forms designer. The Solution Explorer is used to
add any other files, folders or any existing item
on the web site.
◼ To add a standard folder, right-click on the
project or folder under which you are going to
add the folder in the Solution Explorer and
choose New Folder.
Continue…

◼ To add an ASP.NET folder, right-click on the


project in the Solution Explorer and select the
folder from the list.
◼ To add an existing item to the site, right-click
on the project or folder under which you are
going to add the item in the Solution Explorer
and select from the dialog box.
Projects and Solutions

◼ A typical ASP.NET application consists of


many items: the web content files (.aspx),
source files (.cs files), assemblies (.dll and .exe
files), data source files (.mdb files),
references, icons, user controls and
miscellaneous other files and folders. All
these files that make up the website are
contained in a Solution.
Continue….

◼ Solutions may contain one or more projects.


A project contains content files, source files,
and other files like data sources and image
files. Generally, the contents of a project are
compiled into an assembly as an executable
file (.exe) or a dynamic link library (.dll) file.
Continue….

Typically a project contains the following


content files:
▪ Page file (.aspx)
▪ User control (.ascx)
▪ Web service (.asmx)
▪ Master page (.master)
▪ Site map (.sitemap)
▪ Website configuration file (.config)
Building and Running a Project

You can execute an application by:


◼ Selecting Start
◼ Selecting Start Without Debugging from the
Debug menu,
◼ pressing F5
◼ Ctrl-F5
The program is built meaning, the .exe or the
.dll files are generated by selecting a command
from the Build menu.
ASP.NET PROGRAMMING

Module I
ASP.NET Web Forms Server Controls
• ASP.NET provides web forms controls that are used
to create HTML components.
• These controls are categories as server and client
based.
• The following table contains the server controls for
the web forms.
Control Name Applicable Events Description

Label None It is used to display text


on the HTML page.

TextBox TextChanged It is used to create a text


input in the form.
Continue….
Button Click, Command It is used to create a button.

LinkButton Click, Command It is used to create a button


that looks similar to the
hyperlink.

ImageButton Click It is used to create an


imagesButton. Here, an
image works as a Button.

Hyperlink None It is used to create a


hyperlink control that
responds to a click event.
Continue….
DropDownList SelectedIndexChanged It is used to create a
dropdown list
control.

ListBox SelectedIndexChanged It is used to create a


ListBox control like
the HTML control.

DataGrid CancelCommand, It used to create a


EditCommand, grid that is used to
DeleteCommand, show data. We can
ItemCommand, also perform paging,
SelectedIndexChanged, sorting, and
PageIndexChanged, formatting very
SortCommand, easily with this
UpdateCommand, control.
ItemCreated,
ItemDataBound
Continue….
DataList CancelCommand, It is used to create
EditCommand, datalist that is
DeleteCommand, non-tabular and used to
ItemCommand, show data.
SelectedIndexChanged,
UpdateCommand,
ItemCreated,
ItemDataBound

CheckBox CheckedChanged It is used to create


checkbox.
CheckBoxList SelectedIndexChanged It is used to create a
group of check boxes
that all work together.

RadioButton CheckedChanged It is used to create radio


button.
Continue….
RadioButtonList SelectedIndexChanged It is used to create a
group of radio button
controls that all work
together.

Image None It is used to show


image within the page.

Panel None It is used to create a


panel that works as a
container.

PlaceHolder None It is used to set


placeholder for the
control.
Continue…
Calendar SelectionChanged, It is used to create a calendar. We
VisibleMonthChanged, can set the default date, move
DayRender forward and backward etc.

AdRotator AdCreated It allows us to specify a list of ads


to display. Each time the user
re-displays the page.

Table None It is used to create table.

XML None It is used to display XML


documents within the HTML.

Literal None It is like a label in that it displays a


literal, but allows us to create new
literals at runtime and place them
into this control.
ASP.NET Web Forms Label
• This control is used to display textual information on
the web forms. To create Label either we can write
code or use the drag and drop facility of visual
studio IDE.
< asp:LabelID="Label1" runat="server" Text="Label" >
</asp:Label>
   Property Description

AccessKey It is used to set keyboard shortcut for the


label.
TabIndex The tab order of the control.

BackColor It is used to set background color of the label.

BorderColor It is used to set border color of the label.


Continue…
BorderWidth It is used to set width of border of the label.

Font It is used to set font for the label text.

ForeColor It is used to set color of the label text.

Text It is used to set text to be shown for the label.

ToolTip It displays the text when mouse is over the label.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.


ASP.NET Web Forms TextBox
• This is an input control which is used to take user input. To
create TextBox either we can write code or use the drag
and drop facility of visual studio IDE.
< asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox> 
 
Property Description

AccessKey It is used to set keyboard shortcut for the


control.
TabIndex The tab order of the control.

BackColor It is used to set background color of the


control.

BorderColor It is used to set border color of the control.


Continue….
BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the


control.
Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

MaxLength It is used to set maximum number of characters


that can be entered.
Readonly It is used to make control readonly.
ASP.NET Web Forms Button
• This control is used to perform events. It is also used to
submit client request to the server. To
create Button either we can write code or use the
drag and drop facility of visual studio IDE.
<asp:ButtonID="Button1" runat="server“ Text="Submit" />

Property Description

AccessKey It is used to set keyboard shortcut for the


control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Continue….

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.


ASP.NET Web Forms HyperLink
• It is a control that is used to create a hyperlink. It
responds to a click event. We can use it to refer any
web page on the server.
• To create HyperLink either we can write code or use
the drag and drop facility of visual studio IDE. 

< asp:HyperLinkID="HyperLink1"  runat="server" 
Text="JavaTpoint" NavigateUrl="www.javatpoint.com" 
>
</asp:HyperLink> 
Continue….
Property Description

AccessKey It is used to set keyboard shortcut for the


control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the
control.
BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the


control.
Continue….
ToolTip It displays the text when mouse is over
the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

NavigateUrl It is used to set navigate URL.

Target Target frame for the navigate url.


ASP.NET Web Forms RadioButton
• It is an input control which is used to takes
input from the user.
• It allows user to select a choice from the
group of choices.
• To create RadioButton we can drag it from
the toolbox of visual studio.
• This is a server side control and ASP.NET
provides own tag to create it.

< asp:RadioButtonID="RadioButton1" runat="server"
  Text="Male"  GroupName="gender"/>  
Continue….
Property Description
AccessKey It is used to set keyboard shortcut for the
control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the
control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
ASP.NET Web Forms Calendar
• It is used to display selectable date in a
calendar. It also shows data associated with
specific date. This control displays a calendar
through which users can move to any day in
any year.
• We can also set Selected Date property that
shows specified date in the calendar.
• To create Calendar we can drag it from the
toolbox of visual studio.
< asp:CalendarID="Calendar1" runat="server" 
SelectedDate="2017-06-15" > </asp:Calendar>  
Continue…
Property Description
AccessKey It is used to set keyboard shortcut for the
control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the


control.
Continue….
Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

NextMonth Text It is used to set text for the next month


button.
TitleFormat It sets format for month title in header.

DayHeaderStyle It is used to set style for the day header


row.
DayStyle It is used to apply style to days.

NextPrevStyle It is used to apply style to the month


navigation buttons.
ASP.NET Web Forms CheckBox
• It is used to get multiple inputs from the user.
It allows user to select choices from the set of
choices.
• It takes user input in yes or no format. It is
useful when we want multiple choices from
the user.
• To create CheckBox we can drag it from the
toolbox in visual studio.

< asp:CheckBox ID="CheckBox2" runat="server" 
Text="J2EE"/>  
Continue…
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
Checked It is used to set check state of the control either true or
false.
ASP.NET LinkButton
• It is a server web control that acts as a hyperlink. It is
used to display a hyperlink-style button control on the
web page. ASP.NET provides a tag to create
LinkButton and has following syntax.

<asp:LinkButton ID="LinkButton1" runat="server" >
javapoint</asp:LinkButton>  
ASP.NET Web Forms FileUpload
• It is an input controller which is used to upload file to
the server. It creates a browse button on the form
that pop up a window to select the file from the
local machine.
• To implement FileUpload we can drag it from the
toolbox in visual studio.
< asp:FileUpload ID="FileUpload1" runat="server"/> 
  Property Description

AccessKey It is used to set keyboard shortcut for the


control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the
control.
BorderColor It is used to set border color of the control.
Continue…
Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

AllowMultiple It is used to allow upload multiple files by setting true


or false
ASP.NET Upload Multiple Files
• ASP.NET FileUpload control provides
AllowMultiple property to upload multiple
files to the server. This property takes either
true or false value.

• The <asp:FileUpload> tag is used to create a


browse button that allows us to upload file.
ASP.NET Download File
• ASP.NET provides implicit
object Response and its methods to
download file from the server.
• We can use these methods in our
application to add a feature of
downloading file from the server to the local
machine.
ASP.NET Session
• In ASP.NET session is a state that is used to store
and retrieve values of a user.
• It helps to identify requests from the same
browser during a time period (session). It is used
to store value for the particular time session. By
default, ASP.NET session state is enabled for all
ASP.NET applications.
• Each created session is stored
in SessionStateItemCollection object. We can
get current session value by
using Session property of Page object.
ASP.NET Cookie
• ASP.NET Cookie is a small bit of text that is used to
store user-specific information. This information can
be read by the web application whenever user visits
the site.
• When a user requests for a web page, web server
sends not just a page, but also a cookie containing
the date and time. This cookie stores in a folder on
the user's hard disk.
• When the user requests for the web page again,
browser looks on the hard drive for the cookie
associated with the web page. Browser stores
separate cookie for each different sites user visited.
• The Cookie is limited to small size and can be used
to store only 4 KB (4096 Bytes) text.
Continue….
• There are two ways to store cookies in
ASP.NET application.
o Cookies collection
o HttpCookie
o We can add Cookie either to Cookies
collection or by creating instance of
HttpCookie class. both work same except
that HttpCookie require Cookie name as
part of the constructor.
ASP.NET DropDownList
• The DropDownList is a web server control
which is used to create an HTML Select
component.
• It allows us to select an option from the
dropdown list.
• It can contain any number of items
• ASP.NET provides a tag to create
DropDownList for web application.
Continue….
• Syntax of DropDownList tag.
<asp:DropDownList id="DropDownList1" runat="server"  
    DataSource="<% databindingexpression %>"  
DataTextField="DataSourceField"  
DataValueField="DataSourceField" 
AutoPostBack="True|False"  
OnSelectedIndexChanged="OnSelectedIndexC
hangedMethod">  

<asp:ListItem value="value" selected="True|False">  
Text  
</asp:ListItem>  
</asp:DropDownList>  
ASP.NET DataList
• The ASP.NET DataList control is a light weight
server side control that works as a container
for data items.
• It is used to display data into a list format to
the web pages.
• It displays data from the data source.
• The data source can be either a DataTable
or a table from database.
ASP.NET DataGrid
• .NET Framework provides DataGrid control
to display data on the web page.
• It was introduced in .NET 1.0 and now has
been deprecated.
• DataGrid is used to display data in scrollable
grid.
• It requires data source to populate data in
the grid.
• It is a server side control and can be
dragged from the toolbox to the web form.
• Data Source for the DataGrid can be either
a DataTable or a database.
ASP.NET

Module I
ASP.NET Web Forms Model
◻ ASP.NET web forms extend the event-driven model
of interaction to the web applications. The browser
submits a web form to the web server and the
server returns a full markup page or HTML page in
response.
◻ All client side user activities are forwarded to the
server for stateful processing. The server processes
the output of the client actions and triggers the
reactions.
Continue…. Page State VS Session State

◻ Now, HTTP is a stateless protocol. ASP.NET


framework helps in storing the information
regarding the state of the application, which consists
of:
Page state
Session state
◻ The page state is the state of the client, i.e., the
content of various input fields in the web form. The
session state is the collective information obtained
from various pages the user visited and worked
with, i.e., the overall session state. To clear the
concept, let us take an example of a shopping cart.
Continue….
◻ User adds items to a shopping cart. Items are
selected from a page, say the items page, and the
total collected items and price are shown on a
different page, say the cart page. Only HTTP
cannot keep track of all the information coming
from various pages. ASP.NET session state and
server side infrastructure keeps track of the
information collected globally over a session.
Continue….
◻ The ASP.NET runtime carries the page state to and
from the server across page requests while
generating ASP.NET runtime codes, and incorporates
the state of the server side components in hidden
fields.
◻ This way, the server becomes aware of the overall
application state and operates in a two-tiered
connected way.
The ASP.NET Component Model
◻ The ASP.NET component model provides various
building blocks of ASP.NET pages. Basically it is an
object model, which describes:
Server side counterparts of almost all HTML
elements or tags, such as <form> and <input>.
Server controls, which help in developing complex
user-interface. For example, the Calendar control or
the Gridview control.
Continue….
◻ ASP.NET is a technology, which works on the .NET
framework that contains all web-related functionalities.
The .NET framework is made of an object-oriented
hierarchy. An ASP.NET web application is made of
pages. When a user requests an ASP.NET page, the IIS
delegates the processing of the page to the ASP.NET
runtime system.
◻ The ASP.NET runtime transforms the .aspx page into an
instance of a class, which inherits from the base class
page of the .NET framework. Therefore, each ASP.NET
page is an object and all its components i.e., the
server-side controls are also objects.
ASP.NET PROGRAMMING

Module I
ASP.NET - Event Handling
⚫ An event is an action or occurrence such as
a mouse click, a key press, mouse
movements, or any system-generated
notification.
⚫ A process communicates through events.
For example, interrupts are
system-generated events.
⚫ When events occur, the application should
be able to respond to it and manage it.
Continue…
⚫ Events in ASP.NET raised at the client machine,
and handled at the server machine. For
example, a user clicks a button displayed in the
browser. A Click event is raised. The browser
handles this client-side event by posting it to
the server.
⚫ The server has a subroutine describing what to
do when the event is raised; it is called the
event-handler. Therefore, when the event
message is transmitted to the server, it checks
whether the Click event has an associated
event handler. If it has, the event handler is
executed.
Event Arguments
⚫ ASP.NET event handlers generally take two
parameters and return void. The first
parameter represents the object raising the
event and the second parameter is event
argument.
⚫ The general syntax of an event is:
private void EventName (object sender,
EventArgs e);
Application and Session Events
The most important application events are:
⚫ Application_Start - It is raised when the
application/website is started.
⚫ Application_End - It is raised when the
application/website is stopped.
Similarly, the most used Session events are:
⚫ Session_Start - It is raised when a user
first requests a page from the application.
⚫ Session_End - It is raised when the
session ends.
Page and Control Events
Common page and control events are:
⚫ DataBinding - It is raised when a control binds to
a data source.
⚫ Disposed - It is raised when the page or the
control is released.
⚫ Error - It is a page event, occurs when an
unhandled exception is thrown.
⚫ Init - It is raised when the page or the control is
initialized.
⚫ Load - It is raised when the page or a control is
loaded.
⚫ PreRender - It is raised when the page or the
control is to be rendered.
⚫ Unload - It is raised when the page or control is
unloaded from memory.
Event Handling Using Controls
⚫ All ASP.NET controls are implemented as
classes, and they have events which are fired
when a user performs a certain action on
them. For example, when a user clicks a
button the 'Click' event is generated.
⚫ For handling events, there are in-built
attributes and event handlers. Event handler
is coded to respond to an event, and take
appropriate action on it.
Continue…
The common control events are:
Event Attribute Controls

Click OnClick Button, image button, link


button, image map

Command OnCommand Button, image button, link


button

TextChanged OnTextChanged Text box

SelectedIndexCha OnSelectedIndexCh Drop-down list, list box,


nged anged radio button list, check box
list.
CheckedChanged OnCheckedChanged Check box, radio button
Continue…
⚫ Some events cause the form to be posted back
to the server immediately, these are called the
postback events. For example, the click event
such as, Button.Click.
⚫ Some events are not posted back to the server
immediately, these are called non-postback
events. For example, the change events or
selection events such as TextBox.TextChanged
or CheckBox.CheckedChanged. The
nonpostback events could be made to post
back immediately by setting their AutoPostBack
property to true.
Default Events
⚫ The default event for the Page object is
Load event. Similarly, every control has a
default event. For example, default event for
the button control is the Click event.
⚫ The default event handler could be created
in Visual Studio, just by double clicking the
control in design view.
Continue…
The following table shows some of the default
events for common controls:
Control Default Event
AdRotator AdCreated
BulletedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
DataGrid SelectedIndexChanged
DataList SelectedIndexChanged
DropDownList SelectedIndexChanged
Continue…

HyperLink Click

ImageButton Click

ImageMap Click

LinkButton Click

ListBox SelectedIndexChanged

Menu MenuItemClick

RadioButton CheckedChanged

RadioButtonList SelectedIndexChanged
Module 2
Validation Controls
Validation
• Validation or data validation means checking or verifying any data
that comes into the computer.
• Data validation is a method for checking the accuracy and quality of
your data, typically performed prior to importing and processing.
Why Validation??
1. Users might ignore an important field and leave it blank.
2. Users might try to type a short string of nonsense to circumvent a
required field check.
3. Users might make an honest mistake, such as entering a typing
error, entering a nonnumeric character in a number field, or
submitting the wrong type of information.
4. Malicious users might try to exploit a weakness in your code by
entering carefully structured wrong values. For example, they might
attempt to cause a specific error that will reveal sensitive
information
Validation
• When you enter data, the browser and/or the web server will check
to see that the data is in the correct format and within the constraints
set by the application. Validation done in the browser is
called client-side validation, while validation done on the server is
called server-side validation.
• If the information is correctly formatted, the application allows the
data to be submitted to the server and (usually) saved in a database;
if the information isn't correctly formatted, it gives the user an error
message explaining what needs to be corrected, and lets them try
again.
Types of validation
• Validation can be classified into two types based on client and server
validation:
• Client side Validation
• Validations performed at Client-Side i.e., browser.
• User gets information immediately as validation performed before a request
is sent to the server.
• Server side Validation
• Server-side validation takes place before data processing in the database.
• This type of validation is used, where client browser dependencies are
involved.
ASP.Net Validation Controls

• A validation control (or validator) determines whether the data in another


web control is in the proper format, before the data is processed.
• ASP.Net provides validation controls .These controls are similar to other
common controls and can be used in the same way.
• A validation server control is used to validate the data of an input control. If
the data does not pass validation, it will display an error message to the
user.
• To perform validation, ASP.NET provides controls that automatically check
user input and require no code. We can also create custom validation for
our application.
Validation Controls
• Validation controls are very useful while submitting data into a
database table. These controls prevent users from submitting the
wrong type of data. There are six validation controls available in the
ASP.NET.
• RequiredFieldValidator
• RangeValidator
• CompareValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary
Hierarchy Model of ASP.NET Validation
controls
• All the ASP.NET Validation controls derive from the WebControl class.
• The WebControl class derive from System.Web.UI.Control, which
itself derives from System.Object.
The BaseValidator Class
• The validation controls are found in the System.Web.UI.WebControls
namespace and inherit from the BaseValidator class.
• BaseValidator class is parent for all ASP.NET validation controls.
• It is abstract class means we cannot directly instantiate BaseValidator.
• All ASP.NET Validation controls inherit methods and properties
of BaseValidator class.
RequiredFieldValidator

• This is an elementary validation control. Almost all the forms have


some fields that are mandatory to be filled up by the user before
proceeding forward.
• The Required Field Validator ensures that such fields are not left
empty.
• The other validation controls do not validate for an empty field. They
validate, when user enter the data.
Syntax of RequiredFieldValidator
RangeValidator

• The RangeValidator control simply specifies the permitted range


within which the input value should fall. This is most helpful for
numeral input values such as age or for Date input values.
• This validator evaluates the value of an input control to check that the
value lies between specified ranges.
• It allows us to check whether the user input is between a specified
upper and lower boundary. This range can be numbers, alphabetic
characters and dates.
Syntax
Three additional properties of this control
1. Type – Specifies the type of data in the input field. The value is converted
to this type before validation. An exception is thrown if the value cannot
be converted to the specified type. The following data types can be
compared in RangeValidator:
1. String
2. Integer
3. Double
4. Date
5. Currency
2. MinimumValue – Specifies the minimum value that the field can hold.
3. MaximumValue – Specifies the maximum value that the field can hold.
Both minimum and maximum values are inclusive invalidations.
CompareValidator

• The CompareValidator control compares the value of one control with


either a fixed value or a value in another control.
• CompareValidator control is used to perform three different types of
validation tasks.

To perform a data type check.


To compare the value entered into a form field against a given fixed value.
To compare the value of one form field against another field.
Syntax
Properties of this control
• ControlToCompare – It holds the ControlToValidate Id of another form of
control. The value of both the form fields is then compared.
• ValueToCompare – A fixed value with which the comparison has to be made.
• Type: The type of value for comparison. Given values are String, Integer,
Double, Date, and Currency.
• Operator – The type of comparison. The allowed values in this attribute are:
• Equal
• NotEqual
• GreaterThan
• GreaterThanEqual
• LessThan
• LessThanEqual
• DataTypeCheck
RegularExpressionValidator

• RegularExpressions, or simply Regex, are patterns that define the


format of the text. If the text is in the same format, Regex returns
true, else false.
• It matches the input text against the pattern specified in the
ValidationExpression property.
• It allows us to check and validate predictable sequences of characters
like: e-mail address, telephone number etc.
• You can check the predefined pattern, such as a phone number,
postal code, e-mail address, dates, and so on. The control uses the
ValidationExpression property to set a valid regular expression that is
applied to the input data.
Syntax
Regular Expressions
• All regular expressions consist of two kinds of characters: literals and
metacharacters.
• Literals represent a specific defined character. For example, if you search
for the string literal "l", you’ll find the character l and nothing else.
• Metacharacters provide the true secret to unlocking the full power of
regular expressions. You’re probably already familiar with two
metacharacters from the DOS world (? and *). Consider the command-line
expression shown here: Del *.*
• The expression *.* contains one literal (the period) and two metacharacters
(the asterisks). This translates as “delete every file that starts with any
number of characters and ends with an extension of any number of
characters (or has no extension at all).”
Fundamental regular expression building
blocks.
Commonly Used Regular Expressions
Example
• An example of a Regex pattern can be ^[a-z][0-9]. This indicates that a
text must start with an alphabet and follow by a numeral.
CustomValidator

• ASP.Net also allows the freedom of writing your own validator. This
eases the task of a developer to validate the form at the client side
itself. It also allows putting more complex validations in place.
Validations that are business or application-specific can be written
using custom validators.
• The custom validation code is written in a function in the code-behind
page and the function name is passed as an attribute to the
CustomValidator class. Custom validation can be done either at the
client-side or the server-side.
Custom Validator
• ClientValidationFunction property specifies that the validation is to be
performed on the client-side. Such validation code must be written in
some scripting language such as JavaScript, VBScript, etc.
• The ServerValidate event handler is used when validation has to be
done on the server-side. The server-side validation routine is written
in C#, VB .Net or any other .Net language
• CustomValidator allows you to perform validation from both the
client-side as well as server-side.
Syntax
Custom validation on the client

• Client-side validation provides immediate feedback, if error occurs.

Steps for custom validation on the client


• Step 1: Drag a Textbox and CustomValidator, set ControlToValidate
and ErrorMessage properties of CustomValidator.

Step 2: Create Javascript function.


• Step 3: Use ClientValidationFunction property of CustomValidator and
attach your javascript function.
Custom validation on the server

• Drag the CustomValidator control on the web page. Set the


ControlToValidate and ErrorMessage property. Double click on the
CustomValidator control; you will get the event handler as:
ValidationSummary

• The ValidationSummary control does not perform any validation. Its


purpose is to display a summary of all the errors on the page.
ValidationSummary
• It allows us to summarize the error messages at a single location.
• Important Properties
• DisplayMode: BulletList, List, and SingleParagraph

HeaderText: Display header text above the validation summary.

ShowMessageBox: It is used to display a popup alert box

ShowSummary: It hides the validation summary in the page.


Summary
• Validation controls are very useful while submitting data into a database
table. These controls prevent users from submitting the wrong type of data.
There are six validation controls available in the ASP.NET.

RequiredFieldValidator
• RangeValidator
• CompareValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary
ToolBox
Thank You
Validation Controls

Module II
Introduction to Validation Controls
⚫ Validation is important part of any
web application. User's input must
always be validated before sending
across different layers of the
application.
⚫ Validation controls are used to,
⚫ Implement presentation logic.
⚫ To validate user input data.
⚫ Data format, data type and data
range is used for validation.
Continue….
⚫ 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


Continue….
⚫ 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.

⚫ ASP.NET validation controls validate the


user input data to ensure that useless,
unauthenticated, or contradictory data
don't get stored.
Validation Controls
⚫ 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:
Continue….
Members Description
ControlToValid Indicates the input control to validate.
ate
Display Indicates how the error message is shown.
EnableClientSc Indicates whether client side validation will take.
ript
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.

SetFocusOnErr It indicates whether in case of an invalid control, the focus


or should switch to the related input control.

ValidationGrou The logical group of multiple validators, where this control


p 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.
MinimumVal It specifies the minimum
ue value of the range.
MaximumVal It specifies the maximum
ue value of the range.
Continue….
⚫ 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
Properties specific properties:
Description
Type It specifies the data type.
ControlToCom It specifies the value of the input control
pare to compare with.
ValueToComp It specifies the constant value to compare
are with.
Operator It specifies the comparison operator, the
available values are: Equal, NotEqual,
GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and
Continue....
⚫ 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 syntax of the control is as given:
<asp:RegularExpressionValidator ID="string"
runat="server" ErrorMessage="string"
ValidationExpression="string"
ValidationGroup="string">
</asp:RegularExpressionValidator>
Continue….
⚫ The following table summarizes the
commonly used syntax constructs for regular
expressions:
Character Description
Escapes
\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.
Continue….
⚫ Apart from single character match, a class of
characters could be specified that can be
matched, called
Metacharacters the 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.
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
Continue….
⚫ The basic syntax for the control is as
given:
<asp:CustomValidator
ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func.
ErrorMessage="CustomValidator">
</asp:CustomValidator>
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.
⚫ The following two mutually inclusive
properties list out the error message:
⚫ ShowSummary : shows the error messages in
specified format.
⚫ ShowMessageBox : shows the error messages in
a separate window.
⚫ The syntax for the control is as given:
<asp:ValidationSummary
Example
⚫ The following example describes a form to be
filled up by all the students of a school,
divided into four houses, for electing the
school president. Here, we use the validation
controls to validate the user input.
⚫ This is the form in design view:
State Management
Module 2
State Management
• The most significant difference between programming for the Web
and programming for the desktop is state management—how you
store information over the lifetime of your application.
• In a traditional Windows application, memory is plentiful and
always available, and you only need to worry about a single user.
• In a web application, thousands of users can simultaneously run
the same application on the same computer (the web server),
each one communicating over a stateless HTTP connection.
• These conditions make it impossible to design a web application
like a traditional Windows program.
State Management
• Whether you are building a traditional Windows application or a Web-based
application, state is what an application knows about the user, their current interaction
with the application, and other pieces of global information.
• What type of information are we referring to here? Information such as who the user
is, where they are in the application, what information they have entered so far, and
other application configuration information.
• When developing a traditional Windows application, maintaining state isn’t an issue
you had to concern yourself with. Storing information about the current user, their
preferences, or information about the current configuration of the application is as
simple as storing the information globally in either variables or as properties of an
object.
• Those global variables remain in memory for the application to use until the
application is terminated or until they are released. Unfortunately, Web applications
are different.
State Management
• Browsers are generally stateless.
• Stateless means, whenever we visit a website, our browser
communicates with the respective server depending on our requested
functionality or the request. The browser communicates with the
respective server using the HTTP or HTTPs protocol.
• But after that response, what's next or what will happen when we visit
that website again after closing our web browser?
• In this case HTTP/HTTPs doesn't remember what website or URL we
visited, or in other words we can say it doesn't hold the state of a
previous website that we visited before closing our browser, that is
called stateless.
State Management
• State management means to preserve state of a control, web
page, object/data, and user in the application explicitly because all
ASP.NET web applications are stateless, i.e., by default, for each
page posted to the server, the state of controls is lost.
• Nowadays all web apps demand a high level of state management
from control to application level.
State Management
• All web applications are stateless. means in asp.net each page
posted to the server, the state of controls is lost.
• We must make web pages which will remember about the user.
Using state management technique we identify each user uniquely
on same web pages. To preserve state of control we use state
management techniques in asp.net.
• State management is a process of maintaining the state of values
between multiple requests of the page or pages.
Levels of State Management
1. Control level: In ASP.NET, by default controls provide state management
automatically.
2. Variable or object level: In ASP.NET, member variables at page level are
stateless and thus we need to maintain state explicitly.
3. Single or multiple page level: State management at single as well as multiple
page level i.e., managing state between page requests.
4. User level: State should be preserved as long as a user is running the
application.
5. Application level: State available for complete application irrespective of the
user, i.e., should be available to all users.
6. Application to application level: State management between or among two
or more applications.
Types of State Management
• There are two types of state management techniques:
• Client Side State Management - It is a way in which the information
which is being added by the user or the information about the
interaction happened between the user and the server is stored on the
client's machine or in the page itself. The server resources (e.g. server's
memory) is not at all utilized during the process.
• Server Side State Management – It is another way in
which ASP.NET provides to store the user's specific information or
the state of the application on the server machine. It completely makes
use of server resources (the server's memory) to store information.
Types of State Management
• Client side
• Hidden Field
• View State
• Cookies
• Control State
• Query Strings
• Server side
• Session
• Application
State Management
Part 2
State Management
• A web application is stateless.
• That means that a new instance of a page is created every time when
we make a request to the server to get the page and after the round
trip our page has been lost immediately.
• All the controls of the Web Page is created and after the round trip
the server destroys all the instances.
• So to retain the values of the controls we use state management
techniques.
ASP.Net State Management Techniques

• ASP.NET provides us with 2 ways to manage the state of an


application. It is basically divided into the 2 categories:
• Client Side State Management.
• Server Side State Management.
Hidden Field

• Hidden field is a control provided by ASP.NET which is used to store


small amounts of data on the client.
• It store one value for the variable and it is a preferable way when a
variable's value is changed frequently.
• Hidden field control is not rendered to the client (browser) and it is
invisible on the browser.
• A hidden field travels with every request like a standard control’s
value.
Hidden Field

• When a page is submitted to the server, the content of a hidden field


is sent in the HTTP form collection along with the values of other
controls. A hidden field acts as a repository for any page-specific
information that you want to store directly in the page.
Hidden Field
• A HiddenField control stores a single variable in its Value property and
must be explicitly added to the page.
• The HiddenField control provides you with a way to store information
in the page without displaying it.
• To put information into a HiddenField control, you set
its Value property to the value you want to store between postbacks.
Disadvantages
• It is easy for a malicious user to see and modify the contents of a
hidden field.
• Do not store any information in a hidden field that is sensitive or that
your application relies on to work properly.
Hidden Fields
• Hidden Fields are similar to a text box but does not get displayed on
the UI.
• However you can see the value of hidden fields when you view page
source in the browser.
• Using Hidden Fields, you can pass information from one page to
another page without the end user's knowledge, primarily for internal
processing.
View State
• The view state is the state of the page and all its controls. It is
automatically maintained across posts by the ASP.NET framework.
• When a page is sent back to the client, the changes in the properties
of the page and its controls are determined, and stored in the value of
a hidden input field named _VIEWSTATE.
• When the page is again posted back, the _VIEWSTATE field is sent to
the server with the HTTP request.
View State
• The view state could be enabled or disabled for:
• The entire application by setting the EnableViewState property in the
<pages> section of web.config file.
• A page by setting the EnableViewState attribute of the Page directive,
as <%@ Page Language="C#" EnableViewState="false" %>
• A control by setting the Control.EnableViewState property.
• It is implemented using a view state object defined by the StateBag
class which defines a collection of view state items. The state bag is a
data structure containing attribute value pairs, stored as strings
associated with objects.
View State
• ViewState objects are used to store page related data which are
preserved between the round trips from client to server and server to
client. View state is maintained as a hidden field in the page.

• View State is the method to preserve the Value of the Page and
Controls between round trips. It is a Page-Level State Management
technique.
View State – Advantages
• Advantages
• Easy to Implement.
• No server resources are required: The View State is contained in a structure
within the page load.
• Enhanced security features: It can be encoded and compressed or Unicode
implementation.
Disadvantages of View State

• Security Risk: The Information of View State can be seen in the page output
source directly. You can manually encrypt and decrypt the contents of a
Hidden Field, but It requires extra coding. If security is a concern then
consider using a Server-Based state Mechanism so that no sensitive
information is sent to the client.
• Performance: Performance is not good if we use a large amount of data
because View State is stored in the page itself and storing a large value can
cause the page to be slow.
• Device limitation: Mobile Devices might not have the memory capacity to
store a large amount of View State data.
• It can store values for the same page only.
When We Should Use View State
• When the data to be stored is small.
• Try to avoid secure data.
How to Enable and Disable View State

• You can enable and disable View State for a single control as well as at the
page level also. To turn off View State for a single control, set the
EnableViewState property of that control to false.

• TextBox1.EnableViewState=false;
• To turn off the View State for an entire page, we need to
set EnableViewState to false of the page directive as shown below:

• <%Page Language="C#" EnableViewState="false";


• View State Data is stored in the form of Base 64 encoding but it is not more
secure, anyone can easily break it.
Summary
• Stores values per control by key name, like a Hashtable.
• Tracks changes to a View State value's initial state.
• Serializes and Deserializes saved data into a hidden form field on the
client.
• Automatically restores View State data on postbacks.
Control State

• The purpose of the control state repository is to cache data necessary


for a control to properly function.
• ControlState is essentially a private ViewState for your control only,
and it is not affected when ViewState is turned off.
• ControlState is used to store small amounts of critical information.
• Heavy usage of ControlState can impact the performance of
application because it involves serialization and deserialization for its
functioning.
Two Methods
• There are two methods you have to implement in your custom
control.
• Load Control State
• Save Control State
How to use control state property
• Control state implementation is simple.
• First override the OnInit() method of the control and add a call for
the Page.RegisterRequiresControlState() method with the instance of
the control to register.
• Then override LoadControlState and SaveControlState in order to save
the required state information.
Query Strings
• A Query string is used to pass the values or information from one
page to another page. They are passed along with URL in clear text.
Query strings provide a simple but limited way of maintaining some
state information. When surfing the internet you should have seen
weird internet addresses such as:

http://www.localhost.com/Webform2.aspx?name=ABC&lastName=X
YZ
This HTML address uses a QueryString property to pass values
between pages.
Query Strings
• A query string is a collection of characters input to a computer or web
browser.
• A Query String is helpful when we want to transfer a value from one
page to another. When we need to pass content between the HTML
pages or aspx Web Forms in the context of ASP.NET, a Query String is
very easy to use and the Query String follows a separating character,
usually a Question Mark (?).
Query Strings
• A query string consists of two parts, field and value, and each of pair separated by ampersand (&).

• The ?(question mark in a query string indicates the beginning of a query string and it's value.

• There is a limit on the Query string length. Hence, Query strings cannot be used to send very long
data.

• Query strings are visible to the user, hence should not be used to send sensitive information such as
a username and password, unless encrypted.

• To retrieve the query string value, use Request object's QueryString property.
• For sending information to other page Response.Redirect() method used and for retrieve
information from url use Request.QueryString() method used.
Cookies

• Cookie is a small text file which is created by the client's browser and
also stored on the client hard disk by the browser.
• It does not use server memory. Generally a cookie is used to identify
users.
Cookies
• A cookie is a small file that stores user information.
• Whenever a user makes a request for a page the first time, the server
creates a cookie and sends it to the client along with the requested
page and the client browser receives that cookie and stores it on the
client machine either permanently or temporarily (persistent or non
persistence).
• The next time the user makes a request for the same site, either the
same or another page, the browser checks the existence of the cookie
for that site in the folder.
• If the cookie exists it sends a request with the same cookie, else that
request is treated as a new request.
Cookies
• Cookies are always sent with the request to the web server and
information can be retrieved from the cookies at the web server.
Every time a user visits a website, cookies are retrieved from the user
machine and help identify the user.

Cookies are useful for storing small amounts of frequently changed


information on the client. The information is sent with the request to
the server.
Types of Cookies

• 1. Persistence Cookie: Cookies which you can set an expiry date time
are called persistence cookies. Persistence cookies are permanently
stored till the time you set.
• 2. Non-Persistence Cookie: Non persistence cookies are not
permanently stored on the user client hard disk folder. It maintains
user information as long as the user accesses the same browser.
When user closes the browser the cookie will be discarded. Non
Persistence cookies are useful for public computers.
Limitations
• The number of cookies allowed is limited and varies according to the
browser.
• Most browsers allow 20 cookies per server in a client's hard disk
folder and the size of a cookie is not more than 4096 bytes or 4 KB of
data that also includes name and value data.
Code – Persistent Cookies
Code- Non – Persistence Cookies
State Management
Part 3 – Session State
Server Side State Management Techniques
• These are the techniques ASP.NET provides to store the user's specific
information or the state of the application on the server machine. It
completely makes use of server resources (the server's memory) to
store information.
• This management technique basically makes use of the following,
• Session State -user specific state that is stored on the server.
• Application State -The information is global of the application and is
available to all users regardless of the identity of the user requesting
the page.
Session State
• ASP.NET allows you to save values by using session state — which is
an instance of the HttpSessionState class
• Session is used to store user's information and/or uniquely identify a
user (or say browser). The Session basically stores the values as a
dictionary collection in key/value pairs. It completely utilizes server
resources to store the data. It is a secure way of storing data, since
the data will never be passed to the client.
• Session state is generally used for storing application data such as
inventory, supplier list, customer record, or shopping cart. It can also
keep information about the user and his preferences, and keep the
track of pending operations.
Session State ID
• The server maintains the state of user information by using a session
ID.
• When users makes a request without a session ID, ASP.NET creates a
session ID and sends it with every request and response to the same
user.
• For each and every user, a separate Session is created, and each and
every Session has its Unique ID. This ID is being stored in the client's
machine using cookies. If there are multiple users who are accessing a
web application, then for each user a separate Session is created.
Session Tracking
• ASP.NET tracks each session using a unique 120-bit identifier. ASP.NET
uses a proprietary algorithm to generate this value, thereby
guaranteeing that the number is unique and it’s random enough that
a malicious user can’t reverse -engineer or “guess” what session ID a
given client will be using.
• This ID is the only piece of session-related information that is
transmitted between the web server and the client.
Using Session State
• For this system to work, the client must present the appropriate
session ID with each request. You can accomplish this in two ways:
• Using cookies: In this case, the session ID is transmitted in a special
cookie (named ASP.NET_SessionId), which ASP.NET creates
automatically when the session collection is used. This is the default.
• Using modified URLs: In this case, the session ID is transmitted in a
specially modified (munged)URL. This allows you to create
applications that use session state with clients that don’t support
cookies.
Using Session State
• You can interact with session state using the
System.Web.SessionState.HttpSessionState class, which is provided in
an ASP.NET web page as the built-in Session object.
Important methods of Session object
• Abandon: It is used to end a user session.
• Clear: It clears all items from Session state.
• Remove: This method is used to remove a particular item from
Session state.
Storing and Retrieving Data in Session Object
Session State
Session state is global to your entire application for the current user.
However, session state can be lost in several ways:
• If the user closes and restarts the browser.
• If the user accesses the same page through a different browser
window, although the session will still exist if a web page is accessed
through the original browser window. Browsers differ on how they
handle this situation.
• If the session times out due to inactivity.
Four session storage mechanisms
• There are four session storage mechanisms provided by ASP.NET:
• In Proc mode
• State Server mode
• SQL Server mode
• Custom mode

• Off Mode
In Process mode
• In proc mode is the default mode provided by ASP.NET.
• InProc means Session state is stored in memory in the same process
as the ASP.NET process. So accessing data is very fast. Another
advantage is that there are no requirements of serialization to store
data in InProc Session Mode.
• If you restart your server, the state information will be lost.
State Server mode
• With this setting, ASP.NET will use a separate Windows service for
state management.
• This service runs on the same web server, but it’s outside the main
ASP.NET process, which gives it a basic level of protection if the
ASP.NET process needs to be restarted.
• The cost is the increased time delay imposed when state information
is transferred between two processes. If you frequently access and
change state information, this can make for a fairly unwelcome
slowdown.
SQL Server mode
• This setting instructs ASP.NET to use an SQL Server database to store
session information, as identified by the sqlConnectionString
attribute.
• This is the most resilient state store but also the slowest by far. To use
this method of state management, you’ll need to have a server with
SQL Server installed.
Custom Session mode
• Generally we should prefer in proc state server mode or SQL Server
mode but if you need to store session data using other than these
techniques then ASP.NET provides a custom session mode.
• This way we have to maintain everything customized even generating
session ID, data store, and also security.
Off
• This setting disables session state management for every page in the
application.
• This can provide a slight performance improvement for websites that
are not using session state.
Session Events in ASP.NET

• To manage a session, ASP.NET provides two events: session_start and


session_end that is written in a special file called Global.asax in the
root directory of the project.
• Session_Start: The Session_start event is raised every time a new user
makes a request without a session ID, i.e., new browser accesses the
application, then a session_start event raised.
• Session_End: The Session_End event is raised when session ends
either because of a time out expiry or explicitly by using
Session.Abandon(). The Session_End event is raised only in the case
of In proc mode not in the state server and SQL Server modes.
Session State Configuration
• You configure session state through the web.config file for your
current application (which is found in the same virtual directory as
the .aspx web page files). The configuration file allows you to set
advanced options such as the timeout and the session state mode.
Web.Config File
• The following listing shows the most important options that you can
set for the <sessionState> element.
Session Time Out property

• By default, the ASP.NET Framework provides 20 minutes as session


timeout.
• We can change this time according to application need.
Be aware that when you increase the value of session timeout property
more memory is consumed by your application. You can specify the
Session timeout in the web configuration file or you can do it
programmatically.
Cookieless Session State

• If a user disables cookies in the browser, then Session state doesn’t


work because by default, Session state depends on cookies.
• The ASP.NET Framework uses the ASP.NET_SessionId cookie identifier
to identity the user while browsing the web. If you want that Session
state should work even when cookies are disabled, then you can use
cookieless sessions.
• You can enable cookieless sessions by adjusting the sessionState
element in the web configuration file as.
Cookieless Session
• In cookieless mode, the session ID will automatically be inserted into
the URL. When ASP.NET receives a request, it will remove the ID,
retrieve the session collection, and forward the request to the
appropriate directory.
You can use session state to accomplish the
following tasks:
• Uniquely identify browser or client-device requests and map them to
an individual session instance on the server.
• Store session-specific data on the server for use across multiple
browser or client-device requests within the same session.
• Raise appropriate session management events. In addition, you can
write application code leveraging these events.
Disabling session state

• Session state can be disabled site wide by setting mode attribute of


the sessionstate element to Off. You can also enable session state on a
per page basis by setting the EnableSessionState directive to true. If it
is specified ReadOnly the page will only have read-only access to
session state.
Advantages of Session
• It stores user states and data to all over the application.
• Easy mechanism to implement and we can store any kind of object.
• Stores every user data separately.
• Session is secure and transparent from user because session object is
stored on the server.
Disadvantages:
• Performance overhead in case of big number of users, because of
session data stored in server memory.
• Overhead involved in serializing and De-Serializing session Data.
Because In case of StateServer and SQLServer session mode we need
to serialize the object before we store.
Thank You
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose
your president"
runat="server" />
</td>
</tr>
<tr>
<td>
Candidate:
</td>
<td>
<asp:DropDownList ID="ddlcandidate"
runat="server" style="width:239px">
<asp:ListItem>Please choose a
candidate</asp:ListItem>
<asp:ListItem>Ajith </asp:ListItem>
<asp:ListItem>Varun</asp:ListItem>
<asp:ListItem>Sanju</asp:ListItem>
<asp:ListItem>Anila</asp:ListItem>
<asp:ListItem>Shilpa</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server" InitialValue="Please
choose a candidate" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
House:
</td>
<td>
<asp:RadioButtonList ID="rblhouse"
runat="server">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server"
ControlToValidate="rblhouse"
ErrorMessage="Enter your house
name"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Class:
</td>
<td>
<asp:TextBox ID="txtclass"
runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="RangeValidator1"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)"
MaximumValue="12" MinimumValue="6"
Type="Integer"></asp:RangeValidator>
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<asp:TextBox ID="txtemail" runat="server"
style="width:250px"></asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtemail"
ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.
\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="center" colspan="3">
<asp:Button ID="Button1" runat="server"
style="text-align: center"
Text="Submit" onclick="Button1_Click"/>
</td>
</tr>
</table>
<asp:ValidationSummary
ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true"
HeaderText="Errors:"/>
<asp:Label ID="lblmsg1" runat="server"
Text=""></asp:Label>
</div>
</form>
</body>
</html>
Module III
An Introduction To Database Programming
Syllabus – Module III
• An introduction to database programming – Introduction to relational
database, how to use SQL to work with data in database.
• Introduction to ADO.NET 4.
• How to use SQL data source, how to use custom statements and
stored procedures
• Data list controls, Data binding, advanced features of a SQL data
source.
ADO .NET
Introduction
• ADO stands for Microsoft ActiveX Data Objects.
• The ADO.NET is one of the Microsoft’s data access technology which
is used to communicate between the .NET Application (Console, WCF,
WPF, Windows, MVC, Web Form, etc.) and data sources such as SQL
Server, Oracle, MySQL, and XML documents.

• ADO.NET is the technology that .NET applications use to interact with


a database.
ADO .NET
• It is a data access technology from Microsoft .NET Framework , which
provides communication between relational and non relational
systems through a common set of components .
• ADO.NET consist of a set of Objects that expose data access services
to the .NET environment.
So…
ADO.NET provides a bridge between the front end controls and the
back end database. The ADO.NET objects encapsulate all the data
access operations and the controls interact with these objects to
display data, thus hiding the details of movement of data.
Data Access Architecture

• The ADO.NET Framework supports two models of Data Access Architecture,


Connection Oriented Data Access Architecture and Disconnected Data
Access Architecture.
• The ADO.NET Disconnected Data Access Architecture far more flexible and
powerful than ADOs Connection Oriented Data Access.
• In Connection Oriented Data Access Architecture the application makes a
connection to the Data Source and then interact with it through SQL
requests using the same connection. In this case the application stays
connected to the database system even when it is not using any Database
Operations.
• On the other hand the disconnected approach makes no attempt to
maintain a connection to the data source.
Data Providers and DataSet
• The two key components of ADO.NET are Data Providers and DataSet.
• The Data Provider classes are meant to work with different kinds of
data sources. They are used to perform all data-management
operations on specific databases.
• DataSet class provides mechanisms for managing data when it is
disconnected from the data source.
So…
ADO.NET provides a bridge between the front end controls and the
back end database. The ADO.NET objects encapsulate all the data
access operations and the controls interact with these objects to
display data, thus hiding the details of movement of data.
Data provider
• A data provider contains Connection, Command, DataAdapter, and
DataReader objects. These four objects provides the functionality of
Data Providers in the ADO.NET.
Data Provider - Connection
• The Connection Object provides physical connection to the Data
Source. Connection object needs the necessary information to
recognize the data source and to log on to it properly, this information
is provided through a connection string.
ASP.NET Sql Server Connection

• The SqlConnection Object handles the part of physical communication


between the ASP.NET application and the SQL Server Database . An
instance of the SqlConnection class in ASP.NET is supported the Data
Provider for SQL Server Database.
• When the connection is established , SQL Commands will execute with the
help of the Command Object and retrieve or manipulate the data in the
database. Once the Database activities is over , Connection should be
closed and release the Data Source resources .
• The Close() method in SqlConnection Class is used to close the Database
Connection. The Close method rolls back any pending transactions and
releases the Connection from the SQL Server Database.
Command
• The Command Object is used to perform SQL statement or stored
procedure to be executed at the Data Source. The command object
provides a number of Execute methods that can be used to perform
the SQL queries in a variety of fashions.
• It provide three methods which are used to execute commands on
the database:
1. ExecuteNonQuery: Executes commands that have no return values
such as INSERT, UPDATE or DELETE
2. ExecuteScalar : Returns a single value from a database query
3. ExecuteReader: Returns a result set by way of a DataReader object
DataAdapter and DataReader

Data Adapter
• DataAdapter Object populates a Dataset Object with results from a
Data Source . It is a special class whose purpose is to bridge the gap
between the disconnected Dataset objects and the physical data
source.
DataReader
• The DataReader Object is a stream-based , forward-only, read-only
retrieval of query results from the Data Source, which do not update
the data. DataReader requires a live connection with the database
and provides a very intelligent way of consuming all or part of the
result set.
Dataset
• DataSet provides a disconnected representation of result sets from
the Data Source, and it is completely independent from the Data
Source. DataSet provides much greater flexibility when dealing with
related Result Sets.
• DataSet contains rows, columns,primary keys, constraints, and
relations with other DataTable objects. It consists of a collection of
DataTable objects that you can relate to each other with DataRelation
objects. The DataAdapter Object provides a bridge between the
DataSet and the Data Source.
Dataset
DataSet
• The DataSet is the central component in the ADO.NET Disconnected
Data Access Architecture.
• A DataSet is an in-memory data store that can hold multiple tables at
the same time.
• DataSets only hold data and do not interact with a Data Source. One
of the key characteristics of the DataSet is that it has no knowledge of
the underlying Data Source that might have been used to populate it.
Thank You
Data Source Controls, Data
Controls and Data Binding
Data Source Controls
A data source control interacts with the data-bound controls and hides the
complex data binding processes.
These are the tools that provide data to the data bound controls and
support execution of operations like insertions, deletions, sorting, and
updates.
Each data source control wraps a particular data provider-relational
databases, XML documents, or custom classes and helps in:
• Managing connection
• Selecting data
• Managing presentation aspects like paging, caching, etc.
• Manipulating data
• Data source controls are server controls that you can drag onto your
page at design time. A data source control does not have a direct
visual component (you use data-bound controls for actual data
display).
• They allow you to declaratively define access to data found in objects,
XML, and databases.
Data Source Controls - Categories
• There are many data source controls available in ASP.NET for
accessing data from SQL Server, from ODBC or OLE DB servers, from
XML files, and from business objects.
• Based on type of data, these controls could be divided into two
categories:
• Hierarchical data source controls
• Table-based data source controls
Hierarchical
• The data source controls used for hierarchical data are:
• XMLDataSource - It allows binding to XML files and strings with or
without schema information.
• SiteMapDataSource - It allows binding to a provider that supplies site
map information.
So,
• The different data sources used in ASP.NET are
1. LinqDataSource: The Language Integrated Query in an ASP.NET web page is possible
using the markup. The insert, update, select, delete commands are supported. Filtering,
sorting and paging of the data are possible.
2. ObjectDataSource: User can work with the objects using the object data source.
3. SqlDataSource: User can work with Microsoft SQL Server, Oracle, OLEDB and Oracle
databases. The sorting, filtering, paging of the data is possible using the data source.
4. AccessDataSource: Working with Microsoft Access Database is possible using the data
source.
5. XmlDataSource: User can work with the XML file when the hierarchical structure needs
to be used as data source.
6. SiteMapDataSource: Site navigation data.
Data Source Views

• Data source views are objects of the DataSourceView class. Which


represent a customized view of data for different data operations
such as sorting, filtering, etc.
• The DataSourceView class serves as the base class for all data source
view classes, which define the capabilities of data source controls.
CanSURPID, Events, Name
ExecuteSUCID, SUID, CanExecute, OnDataSourceViewChanged
The SqlDataSource Control

• The SqlDataSource control represents a connection to a relational


database such as SQL Server or Oracle database, or data accessible
through OLEDB or Open Database Connectivity (ODBC). Connection to
data is made through two important properties ConnectionString and
ProviderName.
• Syntax
Data Binding

• Every ASP.NET web form control inherits the DataBind method from
its parent Control class, which gives it an inherent capability to bind
data to at least one of its properties. This is known as simple data
binding or inline data binding.
• Simple data binding involves attaching any collection (item collection)
which implements the IEnumerable interface, or the DataSet and
DataTable classes to the DataSource property of the control.
Declarative data binding.

• Some controls can bind records, lists, or columns of data into their
structure through a DataSource control. These controls derive from
the BaseDataBoundControl class. This is called declarative data
binding.
• The data source controls help the data-bound controls implement
functionalities such as, sorting, paging, and editing data collections.
Simple Data Binding

• Simple data binding involves the read-only selection lists. These


controls can bind to an array list or fields from a database.
• Selection lists takes two values from the database or the data source;
one value is displayed by the list and the other is considered as the
value corresponding to the display.
Data Binding
The data binding involves the following objects:
• A dataset that stores the data retrieved from the database.
• The data provider, which retrieves data from the database by using a
command over a connection.
• The data adapter that issues the select statement stored in the
command object; it is also capable of update the data in a database
by issuing Insert, Delete, and Update statements.
Data Bound Controls
• Databound controls are used to display data to the end-user within
the web applications and using databound controls allows you to
manipulate the data within the web applications very easily.
• Databound controls are bound to the DataSource property.
Databound controls are composite controls that combine other
ASP.NET Controls like Text boxes, Radio buttons, Buttons and so on.
Binding a Data-bound Web Server Control to
Data
• You can work with a data-bound control by binding it to a data source
control such as an ObjectDataSource or SqlDataSource control.
• The data source control connects to a data source such as a database or
middle-tier object and then retrieves or updates data.
• The data-bound control can then use this data.
• To perform the binding, you set the data-bound
control's DataSourceID property to point to a data source control.
• When a data-bound control is bound to a data source control, little or no
additional code is required for data operations, because the data-bound
control can automatically take advantage of the data services provided by
the data source control.
Databound controls:
1. Repeater
2. DataList
3. GridView
4. List View
5. Form View
Repeater
• Repeater controls is a Databound control to just display data in the
web application, using this we cannot manipulate the data; in other
words, a Repeater is a read-only control.
• Repeater is very light-weight and faster to display data compared with
other controls, so whenever you just want to display a repeated list of
items then use a Repeater Control.
• Repeater Control appearance is controlled by its templates
GridView Control

• The GridView control displays data as a table and provides the


capability to sort columns, page through data, and edit or delete a
single record.
DetailsView Control

• The DetailsView control renders a single record at a time as a table


and provides the capability to page through multiple records, as well
as to insert, update, and delete records.
FormView Control

• The FormView control renders a single record at a time from a data source
and provides the capability to page through multiple records, as well as to
insert, update, and delete records, similar to the DetailsView control.
• However, the difference between the FormView and
the DetailsView controls is that the DetailsView control uses a table-based
layout where each field of the data record is displayed as a row in the
control.
• In contrast, the FormView control does not specify a pre-defined layout for
displaying a record. Instead, you create templates that contain controls to
display individual fields from the record. The template contains the
formatting, controls, and binding expressions used to lay out the form.
DataList Control

• The DataList control renders data as table and enables you to display
data records in different layouts, such as ordering them in columns or
rows.
• You can configure the DataList control to enable users to edit or
delete a record in the table. (The DataList control does not take
advantage of the capabilities of data source controls for modifying
data; you must supply this code yourself.)
• The DataList control differs from the Repeater control in that
the DataList control explicitly places items in an HTML table, where as
the Repeater control does not.
ListView Control

• The ListView control displays data from a data source in a format that
you define using templates.
• The template contains the formatting, controls, and binding
expressions that are used to lay out the data.
• The ListView control is useful for data in any repeating structure,
similar to the DataList and Repeater controls.
• However, unlike the DataList and Repeater controls,
the ListView control implicitly supports edit, insert, and delete
operations, as well as sorting and paging functionality.
Templates
• Most Web server controls have a default look and layout, which you can
manipulate by setting properties or by using styles. Some Web server
controls also allow you to customize their look by using templates.
• A template is a set of HTML elements and controls that make up the layout
for a particular portion of a control.
• For example, in the DataList Web server control you can use a combination
of HTML elements and controls to create the layout for each row of the list.
• Similarly, the GridView Web server control has a default look for rows in the
grid. However, you can customize the grid's look by defining different
templates for individual columns.
Templates
• Templates consist of HTML and embedded server controls. When the
control runs in the ASP.NET Web page, the control infrastructure
renders the contents of the template in place of the default HTML for
the control.
Templates
• Itemtemplate: An Itemtemplate represents items in a Data Source; an
Itemtemplate renders in the web page as a number of records from
the Datasource Collection
Alternatiningtemplate: Applies a background-color or border-styles
to alternative rows in the Data Source collection
Headertemplate: HeaderTemplate is used to provide Headertext for
the data source collection
Footertemplate: Display footer text to the Data Source.
Data Controls
DataList Controls
• The ASP.NET DataList control is a light weight server side control that
works as a container for data items. It is used to display data into a list
format to the web pages.
• It displays data from the data source.
DataList Control
• DataList is a Databound control to display and manipulate data in a
web application.
• It is a composite control that can combine other ASP.Net controls and
it is present in the form.
• The DataList appearance is controlled by its template fields.
• The DataList control adds a table around the data items by default.
Template fields
• The following template fields are supported by the DataList control:

• Itemtemplate: It specifies the Items present in the Datasource, it renders


itself in the browser as many rows present in the data source collection.
• EditItemTemplate: Used to provide edit permissions to the user.
• HeaderTemplate: Used to display header text to the data source collection.
• FooterTemplate: Used to display footer text to the data source collection.
• ItemStyle: Used to apply styles to an ItemTemplate.
• EditStyle: Used to apply styles to an EditItemTemplate
• HeaderStyle: Used to apply styles to a HeaderTemplate
• Footer Style: Used to apply styles to a FooterTemplate.
Frequently used properties with DataList
Frequently used Events with DataList control
DataList control and Repeat Layouts
The DataList control supports different Repeat Layouts
• Table – This is the default layout. The Table layout renders the
DataList as an HTML Table and its items are rendered inside the Table
Cell. The number of Cells in each row can be set using
the RepeatColumns property.
• Flow – The Flow layout does not render the DataList as any HTML
element. All the DataList items are rendered directly just as how the
Repeater control repeats its items.
• OrderedList and UnorderedList – The OrderedList and UnorderedList
layouts renders the DataList as HTML Ordered List and Unordered
List. But in .Net 4.0 and above these are no longer supported.
Code for Data List and Output
Form View Control
• The FormView control is used to display a single record at a time from
a data source.
• When you use the FormView control, you create templates to display
and edit data-bound values.
• The templates contain controls, binding expressions, and formatting
that define the look and functionality of the form.
Form View Control
• We use the FormView control to do anything that we also can do with
the DetailsView control.
• Just as we can with the DetailsView control, we can use the FormView
control to display, page, edit, insert, and delete database records.
• However, unlike the DetailsView control, the FormView control is
entirely template driven.
• The FormView control provides us with more control over the layout
of a form. Furthermore, adding validation controls to a FormView is
easier than adding validation controls to a DetailsView control.
Binding FormView control to data source

• There are two ways of data binding of FormView control: using


of DataSourceID property or by using of DataSource property.
• Using the DataSourceID property is recommended way because it
enables easier paging and updating.
• When DataSourceID property is used, FormView control supports two
way data binding, so in addition to showing the data, control will
automatically support edit, insert and delete operations.
• Set FormView's DataSourceID property to the name of your data
source control.
Form View Control
• If your FormView control needs to show data in read-only mode only,
set just SelectCommand property of data source control.
• If you also want to modify records, delete or add new items you need
UpdateCommand, DeleteCommand and InsertCommand as well.
List View Control
List View Control
• The ListView control displays columns and rows of data and allows
sorting and paging.
• It is by far the most popular data display control, and is ideal for
understanding how data display controls interact with data retrieval
controls and code.
• ListView can display data items individually or it can group data items.
List View Control
• Most powerful data binding control which has the power of easier
data-binding, flexible pagination, sorting, inserting, deleting, and
updating and CSS implement features.
• Example of a list view
Features of ListView Control
• Can define our own template/Layout/Structure for the data display.
• Edit/Update/Delete capabilities on the data displayed.
• Built-in support for inserting new row.
• Built-in support for sorting
• Supports databinding via DataSource Controls including LINQ
DataSource controls.
• Paging via DataPager control, which can be part of ListView control or
can be kept outside the control. Means, DataPager can be kept at any
part of page as opposed to GridView where the built-in paging is
packed with the control itself.
List View Control
• We can format data using templates and styles in a ListView control.
ListView is popular for display data in any repeating structure. It is a similar
server control to the DataList and Repeater server control. But ListView has
more facility such as user can edit, update, insert, delete, sort and even
page data. All those are ListView built in feature, so you don't need to code
for any one facility.
ListView can data bind with SqlDataSource control using it's DataSourceID
property. By binding data with data source control we can get it's built in
advantage such as paging data, sorting data, inserting, deleting and editing
data.
ListView DataSource property allow us to data bind with many objects such
as ADO.NET DataSet and DataReader. But if you use DataSource property,
you need to write code for paging, sorting, editing etc functionality.
List View Templates
• ListView allow .NET developers to display data as individual items or
in groups. Developers can define data items by templates. ListView
templates similar as DataList and Repeater control.

If you use ListView layout template then you need to create a


LayoutTemplate. The LayoutTemplate must have control that act as a
data place holder. PlaceHolder output each item as defined
ItemTemplate. GroupTemplate allow .NET developers to group
ListView data.
Templates
• ListView control used templates are LayoutTemplate, ItemTemplate,
ItemSeparatorTemplate, GroupTemplate, GroupSeparatorTemplate,
EmptyItemTemplate, EmptyDataTemplate, SelectedItemTemplate.
• To enable ListView data paging we can use DataPager server control
inside LayoutTemplate.
• EditItemTemplate allow us to edit ListView data and
InsertItemTemplate allow to insert new data
In short..
• ListView control can be thought as a hybrid between GridView and
Repeater control.
• ListView control gives us more control on the rendered HTML output
with edit/update/delete feature.
Thank You
Membership
Membership
• As convenient as forms authentication is, it isn’t a complete solution.
It’s still up to the developer to take care of a variety of related tasks.
• For example, you need to maintain a user list and check it during the
authentication process. You also need to create the login page, decide
how to separate public from private content, and decide what each
user should be allowed to do. These tasks aren’t insurmountable, but
can be tedious.
• That’s why Microsoft adds another layer of features to its forms
authentication framework.
• This extra layer is known as membership.
Membership Features
• User record management: Rather than create your own user database, if you use
the membership features, ASP.NET can create and maintain this catalog of user
information. It can even implement advanced rules (such as requiring e-mail
addresses, asking security questions, and implementing strong passwords).
• Security controls: Every secure website needs a login page. With ASP.NET’s security
controls, you don’t need to design your own—instead, you can use a ready-made
version straight from the Login section of the Toolbox. And along with the basic
Login control are other controls for displaying secure content, creating new users,
and changing passwords.
• Role-based security: In many websites, you need to give different permissions to
different users. So it’s useful to assemble users into groups that define certain
permissions. These groups are called roles, and ASP.NET’s membership features
include tools for automatically creating a database with role information.
The Membership Data Store
• The key membership feature is the ability of ASP.NET to store user
credentials in a database. The idea is that you make a few choices
about the information that will be stored and the security policy that
will be used.
• From that point on, ASP.NET manages the user database for
you—adding new user information, checking credentials when users
try to log in, and so on.
• The membership data store has the ability to greatly reduce the
amount of code you need to write. You can create a secure website
with much less code and, hence, much less work
Membership with SQL Server Express
• If you decide to use membership, you need to create the membership
database. If you’re using SQL Server Express (the free version of SQL Server
that’s included with Visual Studio), it all happens automatically.
• By default, membership is enabled for every new website you create. The
default membership provider makes the following assumptions:
a) You want to store your membership database using SQL Server Express.
b) SQL Server Express is installed on the current computer, with the
instance name SQLEXPRESS.
c) Your membership data store will be a file named aspnetdb.mdf, which
will be stored in the App_Data subfolder in your web application
directory.
CreateUserWizard control
• To see how this works, it helps to create a new web project with a
simple test page. Drag the CreateUserWizard control onto your page
from the Login section of the Toolbox. Now run the page without
adding any code or configuring the control.
The Membership and MembershipUser
Classes
• Membership is a useful class that’s full of practical static methods
such as CreateUser(). You can find it in the System.Web.Security
namespace
The Membership class methods
MembershipUser class
• Many of these methods use the MembershipUser class, which
represents a user record. For example, when you call GetUser(), you
receive the information as a MembershipUser object.
• If you want to update that user, you can change its properties and
then call Membership.UpdateUser() with the modified
MembershipUser object.
So
This membership services is an important feature of ASP.NET that helps you
validating and storing user credentials.

The ASP.NET Membership services helps to implement the following functionalities


in an application.
• To create new user and password
• To store the membership information ,such as username ,password ,address,
email and supporting data
• To authenticate and authorization the visitors of the websites.
• It allows the user to create and reset the password
• It allows to create a unique Identification system for authenticated users
The Security Controls
• These controls interact with the membership provider using the
methods of the Membership and MembershipUser classes to
implement common bits of user interfaces such as a login page, a set
of user creation controls, and a password recovery wizard.
Login Control
• A Login control is a control that pairs a user name and a password
text box with a login button.
• The Login control also adds a few features:
• It includes validator controls that prevent the page from being posted back
until a user name and password have been entered. These validators use
client-side validation if it’s supported by the browser (with the help of a bit of
JavaScript) and server-side validation.
Login Control Features
• It automatically handles the signing in and redirection process when
the user logs in successfully. If invalid login credentials are entered, it
shows an error message.
• It provides a Remember Me check box that, if selected, stores a
persistent cookie that remains indefinitely on the user’s computer;
therefore, the user doesn’t need to log back in at the beginning of
each visit.
Markup of Login Control
The CreateUserWizard Control
• The CreateUserWizard control operates in two steps. The first step
collects the user information that’s needed to generate the user
record.
• The second step displays a confirmation message once the account is
created.
Three types of properties
• Style properties that format just a section of the control: For example,
TitleTextStyle configures how the text heading is formatted.
• Properties that set the text for the control: For example, you can
configure each label, the success text, and the messages shown under
different error conditions. You can also retrieve or set the values in
each text box.
• Properties that hide or show a part of the control: For example, you
can use DisplaySideBar, DisplayCancelButton, and RequireEmail to
show or hide the sidebar, cancel button, and e-mail text box,
respectively.
The markup for the basic CreateUserWizard:
Properties of the Control

• Answer: It retrieves or specifies the answer to the password recovery


confirmation question.
• CompleteStep: It shows the final step of the process for creating the
user account.
• ContinueButtonText: It accesses or specifies the collection of
properties defining the look of the control
• Email: It retrieves the email address of the user
• LoginCreatedUser: It accesses or specifies the value indicating the
new user login once the account is created.
Events of the control
• CreatedUser: It is initiated after the membership service provider has
created a new user account
• CreatingUser: It is initiated before the membership service provider is
called for creating user account
• SendingMail: It is initiated before sending the conformation email on
the successful creation of the account
• SendMailError: It is initiated when the SMTP error occurs during the
mail sent to the user.
Thank You
Membership
Login Controls
Part 2
Introduction
• ASP.NET comes with several new security controls (located under the
Login tab in the Toolbox) that greatly simplify the life of a Web
developer.
• Using the new security controls, you can now perform tasks such as
user logins, registration, password changes, and more, with no more
effort than dragging and dropping controls onto your Web form.
• The ASP.NET login controls work together to provide a robust
complete login solution for your ASP.NET Web applications that
requires no programming.
• By default, login controls integrate with ASP.NET membership to help
automate user authentication for your Web site.
Login Controls
Login Controls
The following are the Login controls developed by the Microsoft which
are used in ASP.NET Website
• Login
• LoginView
• LoginStatus
• Loginname
• PasswordRecovery
• ChangePassword
• CreateUserWizard
Login Control
• The Login control displays a user interface for user authentication.
The Login control contains text boxes for the user name and password
and a check box that allows users to indicate whether they want the
server to store their identity using ASP.NET membership and
automatically be authenticated the next time they visit the site.
Login View
• The LoginView Control is a web server control ,which is used to
display two different views of a web page of any website , depending
on whether the any user has logged on to a web page as anonymous
user or registered user .
Login View Templates
• If the user is authenticated, the control displays the appropriate
content to the person with the help of the following views template.
• Anonymous Template :- This template (default of all) will be
displayed when any user just open the web page but not logged in.
• LoggedInTemplate:- This Template (page)will be displayed when the
user is logged in.
• RoleGroups:- This template will be displayed when user logged in,
that is the member of the specific role (defined role group).
LoginView Class
Methods of the LoginView class
• DataBind: It helps user to bind the data source through the LoginView control.
• OnViewChanged: It raises the ViewChanged event after the view for the control is changed.
• OnViewChanging: It raises the ViewChanging event before the LoginView control changes the view.
Properties of the LoginView class
• Controls: It accesses the ControlCollection object containing the child controls for the LoginView
control
• EnableTheming: It access or specifies the value indicating the themes to be applied to the control
• RoleGroups: It access the collection of role groups associated with the content templates
Events of the LoginView class
• ViewChanged: It is initiated when the view is changed
• ViewChanging: It is initiated when the view is in the process to be changed.
The LoginStatus Control
• The LoginStatus control specifies whether a particular user has
logged on the website or not . When the user is not logged in, this
control display the Login text as a hyperlink.
• When the user is logged in ,this control display the logout text as a
hyperlink.
To do this ,Login Status control uses the authentication section of
the web.config file.
This control provides the following two views:-
• LoggedIn --> It will be displayed, when the user is not Logged In.
• Logout --> It will be displayed when the user is Logged In.
The LoginStatus Control
Login Status
Methods of the LoginStatus Control
• OnLoggedOut: It raises the event when the logout link is clicked by the user.
• OnLoggingOut: It raises the event when the user clicks the logout link of the control.
Properties of the LoginStatus Control
• LoginImageUrl: It accesses or specifies the URL of the image used for the login link.
• LoginText: It access the text added for the login link
• LogoutAction: It retrieves the value for determining the action when the user logs out of the web
site.
• LogoutText: It retrieves the text used for logout the link
Events of the LoginStatus Control
• LogginOut: It is initiated when the user sends the logout request to the server.
• LoggedOut: It is initiated by the LoginStatus class when the user logout process is completed
The LoginName Control
• The LoginName Control is responsible for display the names of all the
authenticated users. If no users id is logged in ,then this control is not
displayed on the page.
• This control uses the page User.Identity.Name namespace to return
the value for the user's name.
• The FormatString property is used for displaying the string in the
control.
PasswordRecovery Control
• The PasswordRecovery control is used to recover or reset the
forgotten password of a user .
• This control does not display the password on the browser, but it
sends the password to the respective email address whatever you
have specified at the time of registration.
This control has included three views as given below:-
UserName :- It refers to the view that accepts the username of a user.
• Question :- It accepts the security questions asked from the users.
• Success :- It display a message to the user that retrieved password has
been set to the user.
Methods of the PasswordRecovery Control
• OnSendingMail: It raises the SendingMail event when the user is
verified and the password is sent to the user.
• OnUserLookupErrror: It raises the UserLookupError when the
username does not match with the one stored in the database,
• OnSendMailError: It raises an error when the mail message is not sent
to the user.
• OnVerifyingUser: It raises the event once the username is submitted,
and the membership provider verification is pending.
Properties and Events
Properties of the control
• Answer: The answer provided by the user to confirm the password recovery
through the valid user
• FailureTextStyle: It accesses the reference to the collection of properties defining
the error text look
• HelpPageIconUrl: It image to be displayed for the link to the password is retrieved
Events of the control
• SendingMail: It is initiated when the server is sending an email message
containing the password once the answer is correct
• AnswerLookupError: It is initiated when the user answer to the question is
incorrect
• VerifyingAnswer: It is initiated when the user has submitted the answer to the
password recovery confirmation question
Passwordrecovery Control
CreateUserWizard control
• This control uses the membership service to create a new user in the
membership data store. The CreateUserWizard control is provides by
the CreateUserWizard class and can be customized by using template
and style properties .Using this control any user can easily create an
account and login to the web page
CreateUserWizard control
CreateUserWizard control
Properties of the Control
• Answer: It retrieves or specifies the answer to the password recovery confirmation question.
• CompleteStep: It shows the final step of the process for creating the user account.
• ContinueButtonText: It accesses or specifies the collection of properties defining the look of the control
• Email: It retrieves the email address of the user
• LoginCreatedUser: It accesses or specifies the value indicating the new user login once the account is created.
Events of the control
• CreatedUser: It is initiated after the membership service provider has created a new user account
• CreatingUser: It is initiated before the membership service provider is called for creating user account
• SendingMail: It is initiated before sending the conformation email on the successful creation of the account
• SendMailError: It is initiated when the SMTP error occurs during the mail sent to the user.
The ChangePassword Control
• Using this control ,user can easily change your existing password (old
password) on the ASP.NET Website.
• This control prompts users to provide the current password first and
then set the new password.
• If the old password is not correct then new password can't be set.
• This is also helps to send the email to the respective users about the
new password. This control is used ChangePassword class.
The ChangePassword Control
The ChangePassword Control
Properties of the control
• CancelDestinationPageUrl: It accesses or retrieves the URL of the page that the user is shown once
it clicks the Cancel button.
• CurrentPassword: It retrieves the current password of a user.
• DisplayUserName: It retrieves the value indicating whether the ChangePassword control should be
display the control and label
• NewPassword: It retrieves the new password entered by the user
• UserName: It shows the username for which the password is to be modified.
Events of the control
• ChangedPassword: It is initiated when the password is changed for the user account.
• ChangePasswordError: It is initiated when there is an error in changing the password for the user
account
• SendMailError: It is initiated when the SMTP error occurs during sending an email message

You might also like