0% found this document useful (0 votes)
3 views41 pages

UNIT 2 - AspNet

The document discusses the importance of form validation in web applications using ASP.NET and C#. It outlines different types of validation (client-side and server-side), various ASP.NET validation controls (such as CompareValidator, RangeValidator, RegularExpressionValidator, and RequiredFieldValidator), and provides examples of their implementation. The document emphasizes the need for validation to ensure user input is accurate and secure before processing.

Uploaded by

d47212918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views41 pages

UNIT 2 - AspNet

The document discusses the importance of form validation in web applications using ASP.NET and C#. It outlines different types of validation (client-side and server-side), various ASP.NET validation controls (such as CompareValidator, RangeValidator, RegularExpressionValidator, and RequiredFieldValidator), and provides examples of their implementation. The document emphasizes the need for validation to ensure user input is accurate and secure before processing.

Uploaded by

d47212918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

WEB Programming with asp.

net and c#

UNIT 2

Form Validation
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.

Validation is of two types

1. Client Side
2. Serve Side

Client side validation is good but we have to be dependent on browser and scripting
language support.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Client side validation is considered convenient for users as they get instant feedback. The
main advantage is that it prevents a page from being postback to the server until the client
validation is executed successfully.

For developer point of view serve side is preferable because it will not fail, it is not
dependent on browser and scripting language.

You can use ASP.NET validation, which will ensure client, and server validation. It work on
both end; first it will work on client validation and than on server validation. At any cost
server validation will work always whether client validation is executed or not. So you have
a safety of validation check.

For client script .NET used JavaScript. WebUIValidation.js file is used for client validation
by .NET

ASP.NET validation controls

Following are the validation controls

ASP.NET CompareValidator Control


This validator evaluates the value of an input control against another input control on the
basis of specified operator.

We can use comparison operators like: less than, equal to, greater than etc.

Note: If the input filed is empty, no validation will be performed.

CompareValidator Properties

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Example

Here, in the following example, we are validating user input by using CompareValidator
controller. Source code of the example is given below.

// compare_validator_demo.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="compare_validator_de


mo.aspx.cs"
2. Inherits="asp.netexample.compare_validator_demo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

7. <style type="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11. .auto-style2 {
12. height: 26px;
13. }
14. .auto-style3 {
15. height: 26px;
16. width: 93px;
17. }
18. .auto-style4 {
19. width: 93px;
20. }
21. </style>
22. </head>
23. <body>
24. <form id="form1" runat="server">
25. <table class="auto-style1">
26. <tr>
27. <td class="auto-style3">
28. First value</td>
29. <td class="auto-style2">
30. <asp:TextBox ID="firstval" runat="server" required="true"></asp:TextBox>
31. </td>
32. </tr>
33. <tr>
34. <td class="auto-style4">
35. Second value</td>
36. <td>
37. <asp:TextBox ID="secondval" runat="server"></asp:TextBox>
38. It should be greater than first value</td>
39. </tr>
40. <tr>
41. <td class="auto-style4"></td>
42. <td>
43. <asp:Button ID="Button1" runat="server" Text="save"/>
44. </td>
45. </tr>
46. </table>
47. < asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="s
econdval"
48. ControlToValidate="firstval" Display="Dynamic" ErrorMessage="Enter valid value" ForeCo
lor="Red"
49. Operator="LessThan" Type="Integer"></asp:CompareValidator>
50. </form>

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

51. </body>
52. </html>

Output:

ASP.NET RangeValidator Control


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.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Note: if the input control is empty, no validation will be performed.

The ControlToValidateproperty is used to specify the control to validate.


The MinimumValue and MaximumValue properties are used to set minimum and
maximum boundaries for the control.

RangeValidator Properties

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.

ControlToValidate It takes ID of control to validate.

ErrorMessage It is used to display error message when validation failed.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Type It is used to set datatype of the control value.

MaximumValue It is used to set upper boundary of the range.

MinimumValue It is used to set lower boundary of the range.

Example

In the following example, we are using RangeValidator to validate user input in specified
range.

// RangeValidator.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RangeValidator.aspx.cs


"
2. Inherits="asp.netexample.RangeValidator" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. height: 82px;
10. }
11. .auto-style2 {
12. width: 100%;
13. }
14. .auto-style3 {
15. width: 89px;
16. }
17. .auto-style4 {
18. margin-left: 80px;
19. }
20. </style>
21. </head>
22. <body>
23. <form id="form1" runat="server">
24. <div class="auto-style1">
25. <p class="auto-style4">
26. Enter value between 100 and 200<br/>
27. </p>
28. <table class="auto-style2">
29. <tr>

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

30. <td class="auto-style3">


31. <asp:Label ID="Label2" runat="server" Text="Enter a value"></asp:Label>
32. </td>
33. <td>
34. <asp:TextBox ID="uesrInput"runat="server"></asp:TextBox>
35. <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="uesrInpu
t"
36. ErrorMessage="Enter value in specified range" ForeColor="Red" MaximumValue="199" Mi
nimumValue="101"
37. SetFocusOnError="True"Type=" Integer"></asp:RangeValidator>
38. </td>
39. </tr>
40. <tr>
41. <td class="auto-style3"> </td>
42. <td>
43. <br/>
44. <asp:Button ID="Button2" runat="server" Text="Save"/>
45. </td>
46. </tr>
47. </table>
48. <br/>
49. <br/>
50. </div>
51. </form>
52. </body>
53. </html>

Output:

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

It throws an error message when the input is not in range.

ASP.NET RegularExpressionValidator Control


This validator is used to validate the value of an input control against the pattern defined by
a regular expression.

It allows us to check and validate predictable sequences of characters like: e-mail address,
telephone number etc.

The ValidationExpression property is used to specify the regular expression, this


expression is used to validate input control.

RegularExpression Properties

Property Description

AccessKey It is used to set keyboard shortcut for the control.

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

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

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

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

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.

ErrorMessage It is used to set error message that display when validation


fails.

ControlToValidate It takes ID of control to validate.

ValidationExpression It is used to set regular expression to determine validity.

Example

Here, in the following example, we are explaining how to use RegularExpressionValidator


control to validate the user input against the given pattern.

// RegularExpressionDemo.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegularExpressionDem


o.aspx.cs"
2. Inherits="asp.netexample.RegularExpressionDemo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <table class="auto-style1">
12. <tr>
13. <td class="auto-style2">Email ID</td>

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

14. <td>
15. <asp:TextBox ID="username" runat="server"></asp:TextBox>
16. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"Con
trolToValidate="username"
17. ErrorMessage="Please enter valid email" ForeColor="Red"ValidationExpression="\w+([-
+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
18. </asp:RegularExpressionValidator>
19. </td>
20. </tr>
21. <tr>
22. <td class="auto-style2"></td>
23. <td>
24. <br/>
25. <asp:Button ID="Button1" runat="server" Text="Save"/>
26. </td>
27. </tr>
28. </table>
29. </div>
30. </form>
31. </body>
32. </html>

Output:

It produces the following output when view in the browser.

It will validate email format as we specified in regular expression. If validation fails, it throws
an error message.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

ASP.NET RequiredFieldValidator Control


This validator is used to make an input control required. It will throw an error if user leaves
input control empty.

It is used to mandate form control required and restrict the user to provide data.

Note: It removes extra spaces from the beginning and end of the input value before
validation is performed.

The ControlToValidateproperty should be set with the ID of control to validate.

RequiredFieldValidator Properties

Property Description

AccessKey It is used to set keyboard shortcut for the control.

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

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

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

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

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.

ErrorMessage It is used to set error message that display when validation fails.

ControlToValidate It takes ID of control to validate.

Example

Here, in the following example, we are explaining RequiredFieldValidator control and


creating to mandatory TextBox controls.

// RequiredFieldValidator.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RequiredFieldValidator


.aspx.cs"
2. Inherits="asp.netexample.RequiredFieldValidator" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11. .auto-style2 {
12. width: 165px;
13. }
14. </style>
15. </head>
16. <body>
17. <form id="form1" runat="server">

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

18. <div>
19. </div>
20. <table class="auto-style1">
21. <tr>
22. <td class="auto-style2">User Name</td>
23. <td>
24. <asp:TextBox ID="username" runat="server"></asp:TextBox>
25. <asp:RequiredFieldValidatorIDasp:RequiredFieldValidatorID="user" runat="server" Con
trolToValidate="username"
26. ErrorMessage="Please enter a user name" ForeColor="Red"></asp:RequiredFieldValidat
or>
27. </td>
28. </tr>
29. <tr>
30. <td class="auto-style2">Password</td>
31. <td>
32. <asp:TextBox ID="password" runat="server"></asp:TextBox>
33. <asp:RequiredFieldValidator ID="pass" runat="server" ControlToValidate="password" E
rrorMessage="Please enter a password"
34. ForeColor="Red"></asp:RequiredFieldValidator>
35. </td>
36. </tr>
37. <tr>
38. <td class="auto-style2"> </td>
39. <td>
40. <br/>
41. <asp:Button ID="Button1" runat="server" Text="login"/>
42. </td>
43. </tr>
44. </table>
45. </form>
46. </body>
47. </html>

Output:

It produces the following output when view in the browser.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

It throws error messages when user login with empty controls.

ASP.NET ValidationSummary Control


This validator is used to display list of all validation errors in the web form.

It allows us to summarize the error messages at a single location.

We can set DisplayMode property to display error messages as a list, bullet list or single
paragraph.

ValidationSummary Properties

This control has following properties.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Property Description

AccessKey It is used to set keyboard shortcut for the control.

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

BorderColor It is used to set border color 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.

ShowMessageBox It displays a message box on error in up-level browsers.

ShowSummary It is used to show summary text on the form page.

ShowValidationErrors It is used to set whether the validation summary should be


shown or not.

Example

The following example explains how to use ValidationSummery control in the application.

// ValidationSummeryDemo.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ValidationSummeryDe


mo.aspx.cs"

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

2. Inherits="asp.netexample.ValidationSummeryDemo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <table class="auto-style1">
13. <tr>
14. <td class="auto-style2">User Name</td>
15. <td>
16. <asp:TextBox ID="username" runat="server"></asp:TextBox>
17. <asp:RequiredFieldValidator ID="user" runat="server" ControlToValidate="username"
18. ErrorMessage="Please enter a user name" ForeColor="Red">*</asp:RequiredFieldValida
tor>
19. </td>
20. </tr>
21. <tr>
22. <td class="auto-style2">Password</td>
23. <td>
24. <asp:TextBox ID="password" runat="server"></asp:TextBox>
25. <asp:RequiredFieldValidator ID="pass" runat="server" ControlToValidate="password"
26. ErrorMessage="Please enter a password" ForeColor="Red">*</asp:RequiredFieldValida
tor>
27. </td>
28. </tr>
29. <tr>
30. <td class="auto-style2">
31. <br/>
32. <asp:Button ID="Button1" runat="server"Text="login"/>
33. </td>
34. <td>
35. <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red"/>
36. <br/>
37. </td>
38. </tr>
39. </table>
40. </form>
41. </body>
42. </html>

Output:

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

It produces the following output when view in the browser.

It throws error summary when user login without credentials.

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.

This is a server side control and ASP.NET provides own tag to create it. The example is given
below.

1. < asp:CalendarID="Calendar1" runat="server" SelectedDate="2017-06-


15" ></asp:Calendar>

Server renders it as the HTML control and produces the following code to the browser.

1. <table id="Calendar1" cellspacing="0" cellpadding="2" title="Calendar"


2. style="border-width:1px;border-style:solid;border-collapse:collapse;">

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

3. <tr><td colspan="7" style="background-color:Silver;">


4. <table cellspacing="0" style="width:100%;border-collapse:collapse;">
5. <tr><td style="width:15%;">
6. <a href="javascript:__doPostBack('Calendar1','V6330')"
7. style="color:Black" title="Go to the previous month"></a> ...

This control has its own properties that are tabled below.

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.

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

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

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.

Calendar Property Window

Example

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

In this example, we are implementing calendar and displaying user selected date to the web
page.

// WebControls.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <h2>Select Date from the Calender</h2>
11. <div>
12. <asp:Calendar ID="Calendar1" runat="server"
13. OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
14. </div>
15. </form>
16. <p>
17. <asp:Label runat="server" ID="ShowDate" ></asp:Label>
18. </p>
19. </body>
20. </html>
Code Behind

// WebControls.aspx.cs

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. public void Calendar1_SelectionChanged(object sender, EventArgs e)
12. {
13. ShowDate.Text = "You Selected: "+Calendar1.SelectedDate.ToString("D");
14. }
15. }
16. }

Output:

This view shows calendar to the browser.

It shows date selected by the user at the web page. A screenshot is attached below.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

AdRotator Control
The AdRotator control randomly selects banner graphics from a list, which is specified in
an external XML schedule file. This external XML schedule file is called the advertisement
file.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

The AdRotator control allows you to specify the advertisement file and the type of window
that the link should follow in the AdvertisementFile and the Target property respectively.
The basic syntax of adding an AdRotator is as follows:

<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />


Before going into the details of the AdRotator control and its properties, let us look into the
construction of the advertisement file.

The Advertisement File

The advertisement file is an XML file, which contains the information about the
advertisements to be displayed.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a
text-based markup language that enables you to store data in a structured format by using
meaningful tags. The term 'extensible' implies that you can extend your ability to describe
a document by defining meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules for creating new markup
languages. It is a meta-markup language. It allows developers to create custom tag sets for
special uses. It structures, stores, and transports the information.
Following is an example of XML file:

<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-defined
tags delineating the data. There are the following standard XML elements that are
commonly used in the advertisement file:

Element Description

Advertisements Encloses the advertisement file.

Ad Delineates separate ad.

ImageUrl The path of image that will be displayed.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

NavigateUrl The link that will be followed when the user clicks the ad.

AlternateText The text that will be displayed instead of the picture if it cannot be
displayed.

Keyword Keyword identifying a group of advertisements. This is used for


filtering.

Impressions The number indicating how often an advertisement will appear.

Height Height of the image to be displayed.

Width Width of the image to be displayed.

Apart from these tags, customs tags with custom attributes could also be included. The
following code illustrates an advertisement file ads.xml:

<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

<AlternateText>Send flowers to Russia</AlternateText>


<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>

<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>

Properties and Events of the AdRotator Class

The AdRotator class is derived from the WebControl class and inherits its properties. Apart
from those, the AdRotator class has the following properties:

Properties Description

AdvertisementFile The path to the advertisement file.

AlternateTextFeild The element name of the field where alternate text is provided. The
default value is AlternateText.

DataMember The name of the specific list of data to be bound when


advertisement file is not used.

DataSource Control from where it would retrieve data.

DataSourceID Id of the control from where it would retrieve data.

Font Specifies the font properties associated with the advertisement


banner control.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

ImageUrlField The element name of the field where the URL for the image is
provided. The default value is ImageUrl.

KeywordFilter For displaying the keyword based ads only.

NavigateUrlField The element name of the field where the URL to navigate to is
provided. The default value is NavigateUrl.

Target The browser window or frame that displays the content of the page
linked.

UniqueID Obtains the unique, hierarchically qualified identifier for the


AdRotator control.

Following are the important events of the AdRotator class:

Events Description

AdCreated It is raised once per round trip to the server after creation of the
control, but before the page is rendered

DataBinding Occurs when the server control binds to a data source.

DataBound Occurs after the server control binds to a data source.

Disposed Occurs when a server control is released from memory, which is the
last stage of the server control lifecycle when an ASP.NET page is
requested

Init Occurs when the server control is initialized, which is the first step
in its lifecycle.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Load Occurs when the server control is loaded into the Page object.

PreRender Occurs after the Control object is loaded but prior to rendering.

Unload Occurs when the server control is unloaded from memory.

Working with AdRotator Control

Create a new web page and place an AdRotator control on it.

<form id="form1" runat="server">


<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile ="~/ads.xml"
onadcreated="AdRotator1_AdCreated" />
</div>
</form>
The ads.xml file and the image files should be located in the root directory of the web site.
Try to execute the above application and observe that each time the page is reloaded, the
ad is changed.

State Management :
State Outline

As I said in the beginning, HTTP is a stateless protocol. It just cleans up or we can say
removes all the resources/references that were serving a specific request in the past. These
resources can be:

 Objects
 Allocated Memory
 Sessions ID's
 Some URL info
and so on.

State Management Types

In ASP.NET there are the following 2 State Management methodologies:

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Client-Side State Management

Whenever we use Client-Side State Management, the state related information will directly
get stored on the client-side. That specific information will travel back and communicate
with every request generated by the user then afterwards provides responses after server-
side communication.

This architecture is something like the following,

Server-Side State Management

Server-Side State Management is different from Client-Side State Management but the
operations and working is somewhat the same in functionality. In Server-Side State
Management all the information is stored in the user memory. Due to this functionality
there is more secure domains at the server side in comparison to Client-Side State
Management.

The structure is something like the following,

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

State Management Scenario

It will be a little difficult to directly evaluate what will be better for our application. We
cannot directly say that we will use client-side or server-side architecture of State
Management.

State Management Techniques

State Management techniques are based on client side and server side. Their functionality
differs depending on the change in state, so here is the hierarchy:

Client-side | Techniques

Client-Side State Management techniques are,

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

 View State
 Hidden field
 Cookies
 Control State
 Query Strings

Server-side | Technique

Server-Side State Management techniques are,

 Session State
 Application State

Now I am defining each and every technique in detail with their reference example.

View State
In general we can say it is used for storing user data in ASP.NET, sometimes in ASP.NET
applications the user wants to maintain or store their data temporarily after a post-back..
In this case VIEW STATE is the most used and preferred way of doing that.

This property is enabled by default but we can make changes depending on our
functionality, what we need to do is just change the EnableViewState value to either TRUE
for enabling it or FALSE for the opposite operation.

Figure: [View State Management]

1. // Page Load Event


2. protected void Page_Load(object sender, EventArgs e)
3. {
4. if (IsPostBack)
5. {

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

6. if (ViewState["count"] != null)
7. {
8. int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
9. View.Text = ViewstateVal.ToString();
10. ViewState["count"]=ViewstateVal.ToString();
11. }
12. else
13. {
14. ViewState["count"] = "1";
15. }
16. }
17. }
18.
19. // Click Event
20. protected void Submit(object sender, EventArgs e)
21. {
22. View.Text=ViewState["count"].ToString();
23. }

Points to Remember

Some of the features of view state are:

 It is page-level State Management


 Used for holding data temporarily
 Can store any type of data
 Property dependent

Session Management :
Session is a State Management Technique. A Session can store the value on the Server. It
can support any type of object to be stored along with our own custom objects. 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.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Now here I am explaining sessions with an example.

Step 1: Open Visual Studio 2010.

Step 2: Then Click on "New Project" -> "WEB" -> "ASP.NET Empty Web Application".

Step 3: Now click on Solution Explorer.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Step 4: Now right-click on the "Add" -> "New Item" -> "Web Form" and add the name of the
web form and I had added 2 Web Form1.aspx and Web Form2.aspx.

Step 5: After adding the web form the following code is added to Web Form1.aspx.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx


.cs" Inherits="Session.WebForm1" %>
2.
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD
/xhtml1-transitional.dtd">
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head id="Head1" runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. User Name:-<asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>
12. <br />
13. <br />
14. Password:-<asp:TextBox ID="tbpwd" runat="server"></asp:TextBox>
15. <br />
16. <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Subm
it" />
17. </div>
18. </form>
19. </body>
20. </html>

And the code is:

1. protected void Button1_Click(object sender, EventArgs e)


2. {
3. //textbox value is stored in Session
4. Session["UserName"] = tbUserName.Text;
5. Session["Pwd"] = tbpwd.Text;
6. Response.Redirect("WebForm2.aspx");
7. }

And then add the following code to Web Form2.aspx.

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx


.cs" Inherits="Session.WebForm2" %>
2.
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD
/xhtml1-transitional.dtd">
4. <html xmlns="http://www.w3.org/1999/xhtml">

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

5. <head id="Head1" runat="server">


6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. User Name:-<asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>
12. <br />
13. <br />
14. Password:-<asp:TextBox ID="tbpwd" runat="server"></asp:TextBox>
15. <br />
16. </div>
17. </form>
18. </body>
19. </html>

And the code of the code behind is:

1. protected void Page_Load(object sender, EventArgs e)


2. {
3. //Session value is assign on the text box
4. if (Session["UserName"] != null)
5. {
6. tbUserName.Text = Session["UserName"].ToString();
7. }
8. if (Session["Pwd"] != null)
9. {
10. tbpwd.Text = Session["Pwd"].ToString();
11. }
12. }

Now to set the session we need to use a config file. We can set the session on one of the
following 2 types of configuration files:

1. Machine Configuration file: Machine Configuration is applied for all application.


2. Application Configuration file: It's applied for only application by application basis.

The following is the configuration of the Web.config file:

1. <system.web>
2. <sessionState mode="SQLServer" sqlConnectionString="Server=DIVS\SQLEXPRESS;
Integrated Security=true"></sessionState>
3. <compilation debug="true" targetFramework="4.0" />
4. </system.web>

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Output

Application State Management :

Application State is a state management technique. Application State is stored in the


memory of the the server and is faster than storing and retrieving information in a database.
Session sate is specific for a single user session, but Application State is for all users and
sessions. Application State does not have a default expiration period. When we close the
worker process the application object will be lost. Technically the data is shared amongst
users by a HTTPApplcationState class and the data can be stored here in a key/value pair.
It can also be accessed using the application property of the HTTPContext class.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

ASP.NET Application State real-life example


Now I am explaining the real-life example. If you want to see the number of users online
then we need to use Application State.

Step 1: Open Visual Studio 2010.

Step 2: Then click on "New Project" > "Web" > "ASP.NET Empty Web Application" .

Step 3: Now click on Solution Explorer.

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Step 4: Now right-click on "Add" > "New Item" > "Web Form" and add the name of the web
form.

Step 5: Now add the Global.asax file. Again go to Solution Explorer and "Add" > "New Item"
> "Global Application Class".

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

Step 6: Now to configure the session we need to use the web.config file as in the following:

1. <sessionState mode="InProc" timeout="20" cookieless="true"></sessionState>

Step 7: Now to count the number of users online we need to use the global.asax file as in
the following:

1. protected void Application_Start(object sender, EventArgs e)


2. {
3. //this event is execute only once when application start and it stores the server m
emory until the worker process is restart
4. Application["user"] = 0;
5. }
6. protected void Session_Start(object sender, EventArgs e)
7. {
8. //when session in start application variable is increased by 1
9. Application.Lock();
10. Application["user"] = (int) Application["user"]+1;
11. Application.UnLock();
12. }
13. protected void Session_End(object sender, EventArgs e)
14. {
15. //when session in end application variable is decrease by 1

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete
WEB Programming with asp.net and c#

16. Application.Lock();
17. Application["user"] = (int)Application["user"] - 1;
18. Application.UnLock();
19. }

Step 8: Now to show the online users we need to use a web form as in the following:

1. protected void Page_Load(object sender, EventArgs e)


2. {
3. Response.Write("The num of users online=" + Application["user"].ToString());
4. }

Output

3ibca 501 Web Programming with Asp.Net and C# Asst. Prof. Pradnya J. Nehete

You might also like