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

Shri D. N.

Institute of Computer Applications, Anand


B. C. A. Semester – V
US05CBCA21 Advanced Web Development Technology
Unit 3
Syllabus Unit 3: State Management, Validation and Login controls

State Management: Using View State, QueryString, Cookies, Session State, Application State and Profile
Validation controls: Required Field Validator, Range validator, Regular Expression validator,
Compare validator, Custom validator, Validation summary
Login Controls : Login, LoginView, PasswordRecovery, LoginStatus, LoginName,
CreateUserWizard, ChangePassword.
Creating and Managing Roles Creating
and Managing Access Rules
Creating and Managing Profile

State Management

All web applications are stateless. It means in asp.net each page posted to the server, the state of controls is
lost. In other word, all users can send request to web server but web server does not know about request
from the coming same user or new user. State management is a process of maintaining the state of values
between multiple requests of the pages.

Types of state management

There are two types of state management techniques: client side and server side.

Client side

1. View State
2. Query Strings
3. Cookies

Server side
4. Session
5. Application
6. Profile Properties

1. View State

ViewState is an important client side state management technique. ViewState is used to store user
data on page at the time of post back of web page. ViewState does not hold the controls; it holds the
values of controls. It does not restore the value to control after page post back. ViewState can hold
the value on single web page, if we go to other page using response.redirect then ViewState will be
null. ViewState stores data on single page.
View State Example in ASP.Net
Open visual studio and design web form with two button control, a textbox and a label control as
shows in below figure.

1
Here, we have two buttons control one for a clear textbox value and second one for a retrieve the
same textbox value after clearing it. Before clearing textbox value store it in ViewState[“name”] and
after clearing it get value from ViewState[“name”] and display in label while clicking display value
button.

C# Code for above example

protected void btnclear_Click(object sender, EventArgs e)


{
ViewState["name"] = txtname.Text;
txtname.Text = "";
}
protected void btndisplay_Click(object sender, EventArgs e)
{
lbl.Text = ViewState["name"].ToString();
}

2. Query string
Query string is a simple way to pass some information from one page to another. The information can
be easily passed to one page to another or to same page. With query string method the information
passed in url of page request.
This method many browsers supports only 255 character length of url in query string. The value passed
will be visible so some time it causes security issue.
For send information to other page Response.Redirect() method used and for retrieve information from
url use Request.QueryString() method used.
In Query String method we can send value to only desired page, and value will be temporarily. So
Query string increases the overall performance of web application.

Syntax of Query String


Send information to other page

Response.Redirect(“nextpage.aspx?name=value”);
Retrieve information from other page

Request.QueryString[“name”].ToString();

2
Query String Example in ASP.Net

Design asp.net web form with a button control along with a textbox control. We will pass textbox
value to nextpage.aspx using query string method and retrieve information from url in nextpage and
display it in label control.

C# code for Query String Example


Write below code on SEND button click events on first page for pass information to other page.

protected void btnsend_Click(object sender, EventArgs e)


{
Response.Redirect(“NextPage.aspx?name=” + txtname.Text);
}
Write below code on Retrieve button for retrieve information from url and display it in label on
Nextpage.aspx.

protected void btnretrieve_Click(object sender, EventArgs e)


{
Label1.Text = “Welcome ” + Request.QueryString[“name”].ToString();
}

Pass multiple values using Query String in ASP.Net

In above example we sent single information using query string. If we want to send multiple values in
url using query string method, check below example.

Syntax to pass multiple values

Response.Redirect(“NextPage.aspx?name=value1&city=value2”);

3
C# code for Query String example

Querystrings.aspx page
protected void btnsend_Click(object sender, EventArgs e)
{
Response.Redirect("NextPage.aspx?name=" + txtname.Text + "&city="+txtcity.Text);
}

NextPage.aspx page
protected void btnretrieve_Click(object sender, EventArgs e)
{
Label1.Text = "Name = " + Request.QueryString["name"].ToString();
Label2.Text = "City = " + Request.QueryString["city"].ToString();
}

3. Cookies

Cookie is a small piece of text information which is stored on user hard drive using users browser for
identify users.
It is used to store user preference information like Username, Password, City and PhoneNo etc on
client machines.Cookie does not use server memory.
This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie"
path.

Ways to store cookies


1. Cookies collection
2. HttpCookie object

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.
4
Common Properties of Cookies

Domain: It is used to associate cookies to domain.


Secure: We can enable secure cookie to set true (HTTPs).
Value: We can manipulate individual cookie.
Values: We can manipulate cookies with key/value pair.
Expires: Which is used to set expire date for the cookies.

Types of Cookies
1. Persistence Cookie
2. Non-Persistence Cookie

1. Persistence Cookie
These types of cookies are permanently stored on user hard drive.
Cookies which have an expiry date time are called persistence cookies. These types of cookies stored user
hard drive permanently till the date time we set.
Example to create persistence cookie

Response.Cookies[“name”].Value = “Meera”;
Response.Cookies[“Meera”].Expires = DateTime.Now.AddMinutes(10);
We can also create same cookies as like below

HttpCookie strname = new HttpCookie(“name”);


strname.Value = “Meera”;
strname.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(strname);
In above code we use Response.Cookies object for create Cookie.
In above example we have set 10 Minute time for Expire Cookie, we can retrieve cookie values up to 10
minutes, after 10 minutes the cookies automatically expires.

2. Non-Persistence Cookie
These types of cookies are not permanently stored on user hard drive. It stores the information up to the user
accessing the same browser. When user closes the browser the cookies will be automatically deleted.
Example to create non-persistence cookie

Response.Cookies[“name”].Value = “Meera”;
We can also create same non-persistence cookies as

HttpCookie strname = new HttpCookie(“name”);


strname.Value = “Meera”;
Response.Cookies.Add(strname);

5
Read Cookie Information

if (Request.Cookies[“name”] != null)
{
Label1.Text = Request.Cookies[“name”].Value;
}
ASP.Net Cookie Example
Open visual studio and design web form as shows below figure for create cookie and retrieve cookie
information.

C# code for Cookie Example


Create Cookie Button C# Code

protected void btncreate_Click(object sender, EventArgs e)


{
Response.Cookies["name"].Value = txtcreatecookie.Text;
Response.Cookies["name"].Expires = DateTime.Now.AddMinutes(1);
Label1.Text = "Cookie Created";
txtcreatecookie.Text = "";
}

Here, we create cookie with name parameter and assign textbox values to name cookie and also set expiry
time 1 minute. The cookie destroyed after 1 minute.

Retrieve Cookie Button Code


protected void btnretrieve_Click(object sender, EventArgs e)
{
if (Request.Cookies["name"] == null)
{
txtretrieve.Text = "No cookie found";
}
else
{
txtretrieve.Text = Request.Cookies["name"].Value;
}
}

On retrieve cookie button checks if cookie value not null then display cookie value in result, but after 1
minute the cookie expires, after 1 minute cookie value will be null and result will be “No cookie found”.

6
Advantages of Cookies

 It’s clear text so user can able to read it.


 We can store user preference information on the client machine.
 It is easy to maintain.
 Fast accessing.

Disadvantages of Cookie

 If user clears cookie information we can't get it back.


 No security.
 Each request will have cookie information with page.

Cookie Limitations

1. Most browsers support cookies of up to 4096 bytes(4KB)


2. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are
discarded.
3. Browser supports 300 cookies towards different websites.
4. Complex type of data not allowed (e.g: dataset), allows only plain text (i.e, cookie allows
only string content)
5. Cookies are browser specific (i.e, one browser type[IE] stored cookies will not be used by
another browser type[firefox]).

4. Session state

Basically a session is a variable used between the client and the server that is stored on the server
side. Now it can be stored either on an Internet Information Service (IIS) server that is by default
our "inproc" mode or it can be stored in a state or SQL Server that is our "outproc" mode. Session
state variables are stored on the web server by default and kept for the life time of a session. Default
time is 20 Minutes.

So a session helps to maintain the user state and data all over the application by storing the
information on the server memory. Also a session can store any kind of information or object on the
server side and is accessible in the entire website.

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.
7
Each created session is stored in SessionStateItemCollection object. We can get current session
value by using Session property of Page object.

The process of maintaining the session state proceeds in the following manner. First the client hits
the website and the information is stored in the session. Then a Session table will be made by default
on the IIS server and in the session IDs of all the users visiting the website will be stored by the
server. Now the next time the client requests some information with the unique session ID from the
server, the server looks in the session providers and retrieves the serialized data from the state server
and type casts the object.

Figure: PROCESS FOR MAINTAINING THE SESSION STATE IN THE APPLICATION

A session is one of the best techniques for State Management because it stores the data as
client-based, in other words the data is stored for every user separately and the data is secured also
because it is on the server.

ASP.NET Session Events

There are 2 types of events available in ASP.NET. We can handle both sessions in a global.asax file.

1. Session_Start(): When the new session is initialized then the session_start event is raised.
2. Session_end(): When the session is Expires then the Session_End event raised.

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. Sessions are identified and tracked with a 120-bit SessionID, which
is passed from client to server and back as cookie or a modified URL. The SessionID is globally
unique and random. The session state object is created from the HttpSessionState class, which
defines a collection of session state items.

The HttpSessionState class has the following properties:

Properties Description
SessionID The unique session identifier.
Item(name) The value of the session state item with the specified name. This is the
default property of the HttpSessionState class.
Count The number of items in the session state collection.
TimeOut Gets and sets the amount of time, in minutes, allowed between requests
before the session-state provider terminates the session.

8
The HttpSessionState class has the following methods:

Methods Description
Add(name, value) Adds an item to the session state collection.
Clear Removes all the items from session state collection.
Remove(name) Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
RemoveAt Deletes an item at a specified index from the session-state collection.

5. Application state

Application State is a state management technique. Application State is stored in the memory of the
server and is faster than storing and retrieving information in a database. Session sate is specific for a
single user session, but Application State is for all users and sessions. Application State does not
have a default expiration period. When we close the worker process the application object will be
lost. Application state allows you to store global objects that can be accessed by any client.
Application state is based on the System.Web.HttpApplicationState class, which is provided in all
web pages through the built-in Application object.

Mostly people use this Application state for the reasons given below.

1. Counting clicking.
2. Store common data
3. To display total online users.
4. Total orders received. Etc.

Application State Life Cycle

Global.asax file: the Global.asax file is used for handling application events or methods.

The events of the Global.asax file are:

1. Application_Start() : This method is invoked initially when first application domain is created.
2. Application_BeginRequest() : After an application has started the first method is executed for every
user.
3. Application_AuthenticateRequest() : It checks to determine whether or not the user is valid.
4. Application_Error() : Whenever an unhandled exception occurs then this event will be called.
5. Application_End() : This method is called before the application ends. This can take place if IIS is
restarted or the application domain is changing.
6. Application_Disposed() : This event is called after the application will be shut down and the .NET
GC is about to reclaim the memory it occupies. Although this is very late to perform any clean-up
but we can use it for safety purposes.

9
How to create Application state key and assign value?

To create a new Application, state key is very simple. You can create and retrieve the value of the
Application state with Key-Value pair dictionary of the objects.

Syntax

To Store information in application state

Application[“KEY”] = VALUE;

Ex: Application[“name”] = “Meera”;


Retrieve information from application state
string str = Application[“key”].ToString();

Example of Application State in ASP.Net


Generally we use application state for calculate how many times a given page has been visited by various
clients.
Design web page in visual studio as shows in below figure.

Here, we calculate total visit of uses visited web page by clicking “Click to Visit” button.
C# Code for Example
protected void btnvisit_Click(object sender, EventArgs e)
{
int count = 0;

if (Application["Visit"] != null)
{
count = Convert.ToInt32(Application["Visit"].ToString());
}

count = count + 1;
Application["Visit"] = count;
Label1.Text = "Total Visit = " + count.ToString();

}
10
Output of Example

Here, above output screen we use different browser for visit same page. The result counter value stored in
Application object so it would be changed simultaneously for both visitors.
In above case some time too many users click button at the same time that time result won’t be accurate.
This situation known as dead lock. To avoid dead lock we use Lock() and UnLock() in application state.

To update correct data and values, we need to lock and unlock the value of the Application state variable.

 Lock()- Lock method is to used to lock the variable to update.


 UnLock()- Unlock method is used to release variable status of lock.

Lock() and UnLock() in Application State


protected void btnvisit_Click(object sender, EventArgs e)
{
Application.Lock();
int cnt = 0;

if (Application["Visit"] != null)
{
cnt = Convert.ToInt32(Application["Visit"].ToString());
}

cnt = cnt + 1;
Application["Visit"] = cnt;

Application.UnLock();
Label1.Text = "Total Visit = " + cnt.ToString();

11
6. Profile Properties (Personalization)

 Personalized content means that the user is displayed the content he might be interested in
based on his preferences and other known information about him.
 To display personalized content about the user is known as Personalization.
 This personalization is provided in ASP.NET by the Profile service.
 To use Profile service in the web site we need to define the properties we want to store and
retrieve in web.config.

Validation
ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or
contradictory data don't get stored. ASP.NET validation controls define an important role in validating the
user input data. Whenever the user gives the input, it must always be validated before sending it across to
various layers of an application. If we get the user input with validation, then chances are that we are
sending the wrong data So, validation is a good idea to do whenever we are taking input from the user.

There are two types of Validation:

1) Client side validation


2) Server side validation

1) Client side validation:

 When validation is done on the client browser, then it is known as Client-Side Validation.
 When validation is done using a script (usually in the form of JavaScript) in the
page that is posted to the end user’s browser to perform validations on the data
entered in the form before the form is posted back to the originating server. Then,
client-side validation has occurred.
 Client-side validation is quick and responsive for the end user.
client-side validation is the more insecure form of validation.
 When a page is generated in an end user’s browser, this end user can look at the
code of the page quite easily (simply by right -clicking his mouse in the browser and
selecting View Code).

2) Server side validation:

 When validation occurs on server, where application resides it is called server side validation.
 The more secure form of validat ion is server-side validation.
 The main advantage of Server-Side Validation is that if the user somehow bypasses the Client-Side
Validation, we can still catch the problem on server-side.
 Server-side provides more security and ensures that no invalid data is processed by the application. Server-
Side Validation is done by writing the custom logic for validating all the input.

The best approach is always to perform client -side validation first and then, after the form
passes and is posted to the server, to perform the validation checks again using server -side
validation.

12
Client side validation vs. server side validation
Server-Side Validation
You can use the validation controls to verify a page automatically when the user submits it or manually in
your code. The first approach is the most common. When using automatic validation, the user receives a normal page
and begins to fill in the input controls. When finished, the user clicks a button to submit the page. Every button has a

CausesValidation property, which can be set to true or false. What happens when the user clicks the button depends on
the value of the CausesValidation property:

• If CausesValidation is false, ASP.NET will ignore the validation controls, the page will be

posted back, and your event-handling code will run normally.

• If CausesValidation is true (the default), ASP.NET will automatically validate the page when the user clicks the
button. It does this by performing the validation for each control on the page. If any control fails to validate, ASP.NET
will return the page with some error information, depending on your settings. Your click event-handling code may or
may not be executed—meaning you’ll have to specifically check in the event handler whether the page is valid.

Client-Side Validation
ASP.NET automatically adds JavaScript code for client-side validation. In this case, when the user clicks a
CausesValidation button, the same error messages will appear without the page needing to be submitted and returned
from the server. This increases the responsiveness of your web page.

However, even if the page validates successfully on the client side, ASP.NET still revalidates it when it’s
received at the server. This is because it’s easy for an experienced user to circumvent client-side validation. For
example, a malicious user might delete the block of

JavaScript validation code and continue working with the page. By performing the validation at both ends,
ASP.NET makes sure your application can be as responsive as possible while also remaining secure.

Overview of the Validation controls


Validation server controls are used to validate user-input. 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.

The syntax for creating a Validation server control is:

<asp:control_name id="some_id" runat="server" />

13
There are different types of validation controls:
1) RequiredFieldValidator
2) RangeValidator
3) CompareValidator
4) RegularExpressionValidator
5) CustomValidator
6) ValidationSummary

Validation Control Description


RequiredFieldValidator It makes sure the user enters data in the associated Data-entry control.
RangeValidator It makes sure that the user-entered data passes validation criteria that you
set yourself.
CompareValidator It uses comparison operates to compare user-entered data to a constant
value or the value in another Data-entry.
RegularExpressionValidator It makes sure that the user-entered data matches a regular expression.
CustomValidator It makes sure that the user-entered data passes validations criteria that
you set yourself.
ValidationSummary It displays the list of all the validation errors on the web page.

Common Properties of validation controls:


Property Description
ControlToValidate Gets or sets the input control to validate.
Display Gets or sets the display behavior of the error message in a validation
control.
EnableClientScript Gets or sets a value indicating whether client-side validation is enabled.
Enabled Gets or sets a value that indicates whether the validation control is
enabled.
ErrorMessage Gets or sets the text for the error message displayed in
a ValidationSummary control when validation fails.
ForeColor Gets or sets the color of the message displayed when validation fails.
IsValid Gets or sets a value that indicates whether the associated input control
passes validation.
SetFocusOnError Gets or sets a value that indicates whether focus is set to the control
specified by the ControlToValidateproperty when validation fails.
Text Gets or sets the text displayed in the validation control when validation
fails.
ValidationGroup Gets or sets the name of the validation group to which this validation
control belongs.

Common Methods of validation controls:


Property Description
Validate It performs validation on the associated input control and updates the IsValid
property.

14
To use this controls, you set the ErrorMessage property to the error message you want to display,
and the ControlToValidate property to the control you want to check.

1) RequiredFieldValidator Control: This is the simplest validation control that makes sure that the users
have entered data into a Data-entry control. Suppose that the users are entering data for buying shoes in
Data-entry control. In that case you may want to make sure that the users enter the number of shoes they
want to buy. If they omit to enter a value, this validation control will display its error message.

This control has an Initial value property, which is set to an empty string (“”) by default. If the data
has not changed from that value when validation occurs, the control displays its error message.

Figure of the RequiredfieldValidator

Properties:
Property Description

InitialValue Specifies the starting value of the input control. Default value is ""

2) RangeValidator Control:

A Range validator tests if thevalue of a Data-Entry control is inside a specified range of values. You
use three main properties- ControToValidate, MinimumValue and maximumValue. The ControlToValidte
property contains the Data-Entry control to validate, MinimumValue and MaximumValue properties hold
the minimum and maximum values of the valid range. If you set one of the MinimumValue and
MaximumValue properties, you also must set the other. Also set the Type property to the data type of the
value to compare, the possible values are the same as for comparison validators.

Figure of the RangeValidator

Properties:

Property Description
MaximumValue Specifies the maximum value of the input control
MinimumValue Specifies the minimum value of the input control

15
Type Specifies the data type of the value to check. The types are:
 Currency
 Date
 Double
 Integer
 String

3) CompareValidator Control:

A CompareValidator compares the value entered by the user into a Data-Entry control with the value
entered into another Data-Entry control or with a constant value. As usual for validation controls, you
indicate the Data-Entry control to validate by setting the ControlToValidate property. If you want to
compare a specific Data-Entry control to another, set the ControlToCompare property to specify the control
to compare with.

You can also compare Date-Entry value to the constant value, for that you have to set the
ValueToCompare property.

Use the Type property to specify the type of comparision to perform. Here are the possibilities:

Operator Discription
Equal Checks if the compared value are equal.
Not Equal Checks if the compared value are not equal.
GreaterThan Checks for the greater than relationship.
GreaterThanEqual Checks for the greater than or equal relationship.
LessThan Checks for the less than relationship.
LessThanEqual Checks for the less than or equal relationship.
DataTypeCheck Compares data types between the value enteres into the Data-Entry
control being validated and the data type specified by the Type property

Figure of the CompareValidator

Properties:

Property Description
ControlToCompare The name of the control to compare with
Operator The type of comparison to perform. The operators are:
 Equal
 GreaterThan
 GreaterThanEqual

16
 LessThan
 LessThanEqual
 NotEqual
 DataTypeCheck
ValueToCompare A specified value to compare with

4) RegularExpressionValidator control :

A RegularExpresson validator control is used to check if the value in Data-Entry control matches a
pattern defined by a regular expression. You use regular expression to see if the text matches a certain
pattern, which is a great way to check if the user has entered text in the way you want.

In general regular expressions are made up of text with embedded codes that start with a back slash
(\) as well as other control codes. For Example:

\b[A-Za-z]+\b

The code for a word boundary is \b and a ‘character class’ is a set of characters surrounded with ‘[’
and ‘]’ that lets you specify what characters you want to accept. So this regular expression will match a word
made up of uppercase and/or lowercase letters here.

Figure of the RegularExpressionValidator

Properties:
Property Description

ValidationExpression Specifies the expression used to validate input control. The expression
validation syntax is different on the client than on the server. JScript is used
on the client. On the server, the language you have specified is used

5) CustomValidator control:

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.
17
 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.

With a custom validator, you set the ClientValidationfunction property to the names of a script
function, such as Javascript or VBscript function. This function will pass two argiuments- sources and
arguments, source, gives the source control to validate, and arguments, hold data to validate as
asguments.Value. if you validate the data, you set arguments.IsValid to TRUE else to FALSE.

Using custom validator is perhaps the most powerful way to use validators. Existing beyond the
simple range checking and field checking validators, custom validators also let you write your own
customization code.

Figure of the CustomValidator

Properties:

Property Description
ClientValidationFunction Specifies the name of the client-side validation script function to be
executed.
Note: The script must be in a language that the browser supports,
such as VBScript or Jscript With VBScript, the function must be in
the form:
Sub FunctionName (source, arguments)
With JScript, the function must be in the form:
Function FunctionName (source, arguments)
ValidateEmptyText Sets a Boolean value indicating whether empty text should be
validated.

Events:
Property Description

ServerValidate It occurs when validation takes place on the server.

18
6) ValidationSummary control:

The Validationsummary control, which summarize the error messages from all validators on a web
page in one location. The summary can be displayed as a list, as a bulleted list, or as a single paragraph,
based on the DisplayMode property. You can alos specify if the summary should be displayed in the web
page and in a message box by setting the ShowSummary and showMessagebox propertises, respectively.

Figure of the ValidationSummary

Properties:

Property Description
DisplayMode How to display the summary. Legal values are:
 BulletList
 List
 SingleParagraph
EnableClientScript A Boolean value that specifies whether client-side validation is
enabled or not
Enabled A Boolean value that specifies whether the validation control is
enabled or not
ForeColor The fore color of the control
HeaderText A header in the ValidationSummary control
ShowMessageBox A Boolean value that specifies whether the summary should be
displayed in a message box or not
ShowSummary A Boolean value that specifies whether the ValidationSummary
control should be displayed or hidden
ValidationGroup Sets the group of controls for which the validationSummary object
displays validation messages.

Login Controls
Internet is emerging as the most widely used medium for performing various tasks, such as
online shopping ,Data exchanging and bank transactions etc. All this Information and data need to be
secured against unauthorized access from illegal sources. For this purpose, we use authentication and
authorization process.

We need to write large piece of code to create forms and user interfaces for authenticating the user and
displaying the desired page based on the roles or rights given to the user. But it is very time consuming so
that Microsoft developed a new series of server controls, called login controls.

To use login controls in your website. You just need to drag and drop them on the web page.
19
There is no need to write more codes in the codes-behind file. The Login controls have built in functionality
for authentication and authorization of users.

The Membership Service

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 Login Controls

1. Login
2. LoginView
3. LoginStatus
4. Loginname
5. PasswordRecovery
6. ChangePassword
7. CreateUserWizard

1.)The Login Control:-

The Login control provides a user interface which contains username and password that authenticate the
username and password and grant the access to the desired services on the basis of the credentials.

The Login class contains various methods, properties, and events to work with. Some of them are as listed
below:

1. CreateChildControls: It creates an individual control of the Login control and the event handlers are
associated with it.
2. OnLoggingIn: It raises the LoggingIn event when the user adds the login data before the
authentication is completed.
3. OnLoggedIn: It raises an LoggedIn event when the user log into the web site after the authentication
is completed
4. OnAuthenticate: It raises an Authenticate event for the user authentication.

Properties of the Login Control

1. CreateUserIconUrl: It retrieves the location of the image to display the link to the user.
2. CreateUserUrl: It specifies or retrieves the URL for the new user page.
3. DisplayRememberMe: It specifies the value stating whether to display the RememberMe checkbox.
4. FailureText: It displays the text when the login attempt fails
5. HelpPageText: It specifies the text of link to the login help page.
6. Password: It retrieves the password entered by the user
20
Events of the Login Control

1. LoggedIn: It is initiated when the user logs in the web site and is authenticated.
2. LoggingIn: It is initiated when the user submits the login information.
3. LoginError: It is initiated when a login error is detected.
The Login control at the design time is as shown below:

2.) The LoginView Control:-

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 .If the user is authenticated, the control displays the appropriate 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 in logged in.
 RoleGroups:- This template will be displayed when user logged in, that is the member of the specific
role (defined role group).

You can drag and drop Loginview Control on the web page from toolbox as shown below:-

The LoginView class provides the LoginView control. The methods, properties and events provided by the
login class are as listed below:

Methods of the LoginView class

1. DataBind: It helps user to bind the data source through the LoginView control.
2. OnViewChanged: It raises the ViewChanged event after the view for the control is changed.

21
3. OnViewChanging: It raises the ViewChanging event before the LoginView control changes the
view.

Properties of the LoginView class

1. Controls: It accesses the ControlCollection object containing the child controls for the LoginView
control
2. EnableTheming: It access or specifies the value indicating the themes to be applied to the control
3. RoleGroups: It access the collection of role groups associated with the content templates.

Events of the LoginView class

1. ViewChanged: It is initiated when the view is changed


2. ViewChanging: It is initiated when the view is in the process to be changed.

3.) The LoginStatus Control :-

It specifies that a particular user has logged into the web site. The login status is displayed as a text. The
login text is displayed as a hyperlink but provides the navigation to the login page. The authentication
section of the web.config file is useful for accessing the login page URL.

The LoggedIn and LoggedOut are the two status provided by the LoginStatus control. The LoginStatus class
provides the control. The methods, properties and events for the control are as mentioned below:

Methods of the LoginStatus Control

1. OnLoggedOut: It raises the event when the logout link is clicked by the user.
2. OnLoggingOut: It raises the event when the user clicks the logout link of the control.

Properties of the LoginStatus Control

1. LoginImageUrl: It accesses or specifies the URL of the image used for the login link.
2. LoginText: It access the text added for the login link
3. LogoutAction: It retrieves the value for determining the action when the user logs out of the web site.
4. LogoutText: It retrieves the text used for logout the link.

Events of the LoginStatus Control

1. LogginOut: It is initiated when the user sends the logout request to the server.
2. LoggedOut: It is initiated by the LoginStatus class when the user logout process is completed

22
The LoginStatus control at the design time is as shown below:

4.) The LoginName Control :-

It is used for displaying the name of the authenticated users. The Page.User.Identity.Name is used for
returning the user name. The control is not displayed if it does not contain any logged in user. The
LoginName class is used for the control.

The control does not contain any method, property or events associated with it. The FormatString property is
used for displaying the string in the control.

The LoginName control at the design time is as shown below:

5.) Passwordrecovery Control:-

It is used to recover or reset the password for the user. The password is sent through an email as a message
at the registration time. The Membership service is used for creating and resetting the password.

The control contains the following three views.

1. Question: It refers the view where the user can enter the answer to the security question.
2. UserName: It refers to the view where the user can enter the username for the password to be
recovered.
3. Success: It represents the view where the message is displayed to the user.
The control contains various properties, methods and events as mentioned below:

Methods of the PasswordRecovery Control

1. OnSendingMail: It raises the SendingMail event when the user is verified and the password is sent to
the user.
2. OnUserLookupErrror: It raises the UserLookupError when the username does not match with the
one stored in the database,
3. OnSendMailError: It raises an error when the mail message is not sent to the user.
23
4. OnVerifyingUser: It raises the event once the username is submitted, and the membership provider
verification is pending.

Properties of the control

1. Answer: The answer provided by the user to confirm the password recovery through the valid user.
2. FailureTextStyle: It accesses the reference to the collection of properties defining the error text look.
3. HelpPageIconUrl: It image to be displayed for the link to the password is retrieved.

Events of the control

1. SendingMail: It is initiated when the server is sending an email message containing the password
once the answer is correct.
2. AnswerLookupError: It is initiated when the user answer to the question is incorrect.
3. VerifyingAnswer: It is initiated when the user has submitted the answer to the password recovery
confirmation question.

The PasswordRecovery control at the design time is as shown below:

6. ) CreateUserWizard control:-

The control uses the Membership service for creation of a new user. The control can be extended to the
existing Wizard control. The control can be customized through templates and properties.

Some of the properties, methods and events related to the control are as mentioned below:

Properties of the Control

1. Answer: It retrieves or specifies the answer to the password recovery confirmation question.
2. CompleteStep: It shows the final step of the process for creating the user account.
3. ContinueButtonText: It accesses or specifies the collection of properties defining the look of the
control
4. Email: It retrieves the email address of the user
5. LoginCreatedUser: It accesses or specifies the value indicating the new user login once the account
is created.

Events of the control

1. CreatedUser: It is initiated after the membership service provider has created a new user account
2. CreatingUser: It is initiated before the membership service provider is called for creating user
account
24
3. SendingMail: It is initiated before sending the conformation email on the successful creation of the
account
4. SendMailError: It is initiated when the SMTP error occurs during the mail sent to the user.

The CreateUserWizard control at the design time is as shown below:

7.) The ChangePassword Control:-

Using this control ,user can easily change your existing password (old password) on the ASP.NET
Website.This control prompts uses to provide the current password first and then set the new 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.

Properties of the control

1. CancelDestinationPageUrl: It accesses or retrieves the URL of the page that the user is shown once it
clicks the Cancel button.
2. CurrentPassword: It retrieves the current password of a user.
3. DisplayUserName: It retrieves the value indicating whether the ChangePassword control should be
display the control and label.
4. NewPassword: It retrieves the new password entered by the user.
5. UserName: It shows the username for which the password is to be modified.

Events of the control

1. ChangedPassword: It is initiated when the password is changed for the user account.
2. ChangePasswordError: It is initiated when there is an error in changing the password for the user
account.
3. SendMailError: It is initiated when the SMTP error occurs during sending an email message.
25
The ChangePassword control at the design time is as shown below:

Implementing Authentication in ASP.NET login controls

Consider an example to demonstrate the login controls in an ASP.NET application. Perform the following
steps to demonstrate the implementation of the login controls in application.

1. Place the login control in the .aspx form and change the AutoFormat style property to Classic.

2. Click the Smart Tag and open the Login Tasks and select the Administer Website option.
3. Click the Security link in the window

4. Click the Use the security Setup Wizard to configure security step by step link to open the setup
wizard

26
5. Click Next button in the welcome the security setup wizard.

6. Click the From the Internet radio button and click the Next button.

7. Click the Next button in the Advance provider settings page.

27
8. Select the Enable roles for this web site check box and click the Next button

9. Add the details in the text boxes and click the Create User button to create the user account.

10. Select the All Users radio button in the Rule applies to section.

28
11. Click the Add this Rule button. Click Next button

12. Click Finish button, click Close button.

13. Add the LoginName and LoginStatus controls on the web page.

14. Set the LogoutAction property to Redirect, click the smart tag of the LoginStatus control and select
the Logged In option from the Views drop down list.

15. Execute the application and enter the username and password in the text boxes. Click Log In button.

16. The following output is displayed when the application is executed on the server.

29

You might also like