ASP.NET CODING MODELS An ASP.NET Web page consists of two parts: 1. Visual elements, which include...

112
ASP.NET CODING MODELS An ASP.NET Web page consists of two parts: 1.Visual elements, which include markup, server controls, and static text. 2. Programming logic for the page, which includes event handlers and other code.

Transcript of ASP.NET CODING MODELS An ASP.NET Web page consists of two parts: 1. Visual elements, which include...

ASP.NET CODING MODELSAn ASP.NET Web page consists of two parts:

1.Visual elements, which include markup, server controls, and static text.

2. Programming logic for the page, which includes event handlers and other code.

ASP.NET CODING MODELS

ASP.NET supports two methods to author pages:

In-line code – (Single File) Code-behind

In-line code – (Single File) try.aspx

<%@ Language=C# %><HTML> <script runat="server" language="C#"> void MyButton_OnClick(Object sender, EventArgs e) { MyLabel.Text = MyTextbox.Text.ToString(); } </script> <body> <form id="MyForm" runat="server"> <asp:textbox id="MyTextbox" text="Hello World"

runat="server"></asp:textbox> <asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick"

runat="server"></asp:button> <asp:label id="MyLabel" runat="server"></asp:label> </form> </body> </HTML>

Code-behind mycodebehind.aspx

<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Class1.cs" Inherits="MyStuff.MyClass" %>

<HTML> <body> <form id="MyForm" runat="server"> <asp:textbox id="MyTextBox" text="Hello World"

runat="server"></asp:textbox> <asp:button id="MyButton" text="Echo Input" Onclick="MyButton_Click"

runat="server"></asp:button> <asp:label id="MyLabel" runat="server" /> </form> </body> </HTML>

MYCODEBEHIND.CSusing System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MyStuff { public partial class MyClass : Page { public void MyButton_Click(Object sender, EventArgs e) { MyLabel.Text = MyTextBox.Text.ToString(); } } }

In the preceding sample, the code-behind page is compiled before ASP.NET runs. Alternatively, you can reference the code-behind class by using an SRC tag as follows:

<%@ Language="C#" Inherits="MyStuff.MyClass" src="MyCodebehind.cs" %>

In this case, ASP.NET compiles the code-behind page on the fly.

Advantages of Single-File Pages As a rule, the single-file model is suitable for pages in

which the code consists primarily of event handlers for the controls on the page.

Advantages of the single-file page model include the following: it can be easier to study a single-file page because you can

see the code and the markup in one place. Pages written using the single-file model are slightly easier

to deploy or to send to another programmer because there is only one file.

Because there is no dependency between files, a single-file page is easier to rename.

Managing files in a source code control system is slightly easier, because the page is self-contained in a single file.

Advantages of Code-Behind PagesCode-behind pages offer advantages that make them suitable for Web applications with significant code or in which multiple developers are creating a Web site.

Advantages of the code-behind model include the following: Code-behind pages offer a clean separation of the markup

(user interface) and code. It is practical to have a designer working on the markup while a programmer writes code.

Code is not exposed to page designers or others who are working only with the page markup.

Code can be reused for multiple pages.

ASP.NET PAGE DIRECTIVES Directives specify settings that are used by the

page and user-control compilers when the compilers process ASP.NET Web Forms pages (.aspx files) and user control (.ascx) files.

ASP.NET treats any directive block (<%@ %>) that does not contain an explicit directive name as an @ Page directive (for a page) or as an @ Control directive (for a user control).

Directive Description

@ AssemblyLinks an assembly to the current page or user control declaratively.

@ Control

Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).

@ Implements

Indicates that a page or user control implements a specified .NET Framework interface declaratively.

@ ImportImports a namespace into a page or user control explicitly.

@ Master

Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.

@ MasterType

Defines the class or virtual path used to type the Master property of a page.

@ OutputCache

Controls the output caching policies of a page or user control declaratively.

AT RUN TIME, MASTER PAGES ARE HANDLED IN THE FOLLOWING SEQUENCE:

1. Users request a page by typing the URL of the content page.

2. When the page is fetched, the @ Page directive is read. If the directive references a master page, the master page is read as well. If this is the first time the pages have been requested, both pages are compiled.

3. The master page with the updated content is merged into the control tree of the content page.

4. The content of individual Content controls is merged into the corresponding ContentPlaceHolder control in the master page.

5. The resulting merged page is rendered to the browser.

@ Page

Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.

@ PreviousPageType

Creates a strongly typed reference to the source page from the target of a cross-page posting.

@ Reference

Links a page, user control, or COM control to the current page or user control declaratively.

@ Register

Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.

<%@ Import namespace="value" %>

The @ Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @ Import directives.

A set of namespaces can be automatically imported into .aspx pages. The imported namespaces are defined in the machine-level Web.config file, within the <namespaces> section of the <pages> element. The following namespaces are automatically imported into all pages:

System System.Collections System.Collections.Specialized System.Configuration System.Text System.Text.RegularExpressions System.Web System.Web.Caching System.Web.Profile System.Web.Security System.Web.SessionState System.Web.UI System.Web.UI.HtmlControls System.Web.UI.WebControls System.Web.UI.WebControls.WebParts

<%@ Implements interface="ValidInterfaceName" %>

PAGE DIRECTIVE

<%@ Page attribute="value" [attribute="value"...] %>

Some of the attributes of page directive are given below

Async Makes the page an asynchronous handler (that is, it causes the page to use an implementation of IHttpAsyncHandler to process requests). The default is false.

AsyncTimeOut Defines the time-out interval (in seconds) used when processing asynchronous tasks. The default is 45 seconds.The value must be an integer.

Language Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the page.

Values can represent any .NET Framework-supported language, including Visual Basic, C#, or JScript.

Only one language can be used and specified per page

Src Specifies a path to a source file containing code that is linked to the page. In the linked source file, you can choose to include programming logic for your page either in a class or in code declaration blocks.

ClassName Specifies the class name for the class that is automatically

generated from the markup and compiled when the master page is processed. This value can be any valid class name and can include a namespace.

CodeFile Specifies the name of a separate file that contains a partial

class with the event handlers and other master page–specific code. For more information, see ASP.NET Web Page Code Model

<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Class1.cs" Inherits="MyStuff.MyClass" %>

POSTBACK POSTING

Every time page is submitted back to itself so that it can run its server code again to produce the new version of itself for the user.

Login form

Combo box - ‘Auto PostBack’ property for that control set = true

script language="VB" runat="server"> Sub Test_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs)  'enter your code to perform End Sub </script>

<html> <body> <form runat="server" id="myForm">      <asp:linkbutton id="Test" runat="server" text="Create

Text file" onclick="Test_Click" />     </form> </body> </html>

<html> <body>     <form name="myForm" method="post" action="test.aspx"

id="myForm">      <input type="hidden" name="__EVENTTARGET" value="" />

<input type="hidden" name="__EVENTARGUMENT" value="" /> <input type="hidden" name="__VIEWSTATE“  value="dDwtMTAwOTA0ODU1NTs7PsllCK1DzvZsK0J6OQ2dxKqmEwVs" />

<script language="javascript"> <!– function __doPostBack(eventTarget, eventArgument) {   var theform = document.myForm;     theform.__EVENTTARGET.value = eventTarget;      theform.__EVENTARGUMENT.value = eventArgument; theform.submit(); } --> </script> <a id="Test" href="javascript:__doPostBack('Test','')">Create Text

file</a> </form> </body> </html>

CROSS PAGE POSTING

When you build dynamic web site you may post one page to another with some information.

E.g baking takes palce with buttons control

CLIENT SIDEResponse.BufferOutput = true; if (UserLanguage == "English") { Response.Redirect("http://www.microsoft.com/gohere/look.htm"); } else if (UserLanguage == "Deutsch") { Response.Redirect("http://www.microsoft.com/gohere/

look_deu.htm"); } else if (UserLanguage == "Español") { Response.Redirect("http://www.microsoft.com/gohere/

look_esp.htm"); }

SERVER SIDE

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

{ Server.Transfer("Page2.aspx", true); }

PAGE EVENTS AND PAGE LIFE CYCLE

When you send a request to the web server for a page , the page runs through series of events during its creation and disposal.

Collection of events as a whole is known as page’s life cycle.

EVENTS

Event Description

PreInit Raised after the start stage is complete and before the initialization stage begins.Use this event for the following: Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.Create or re-create dynamic controls.Set a master page dynamically.Set the Theme property dynamically.Read or set profile property values.

Init Raised after all controls have been initialized. Use this event to read or initialize control properties

InitComplete

Raised at the end of the page's initialization stage. Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad This event is used to perform processing on your page or on control before the load event is raised. After this event is raise page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load Use the OnLoad event method to set properties in controls and to establish database connections. The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded.

Control Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

LoadComplete

Raised at the end of the event-handling stage.Use this event for tasks that require that all other controls on the page be loaded.

PreRender This event is raised for each control on the page. Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

SaveStateComplete

Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Unload Raised for each control and then for the page.In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

EXAMPLE OF PAGE_LOAD

using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;

namespace WebApplication3{ public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs

e) {

} }}

APPLICATION COMPILATION MODELS Normal compilation Model –

Code behind file – compiled - /bin , web page compilation on demand

first request slow ASP .NE 2.0 still support

Deployment Pre-Compilation Full compilation prior to deploymentAssemblies contain compiled code and resource filesConfiguration files are copied without making

modification Full Run Time Compilation

compiles entire application at run time uncomplied files (code behind and code files) in \

App_Codeassemblies get created and maintained at run time – flexibility

ASP.NET CONTROLS Custom Control - Programmers can also build custom controls

for ASP.NET applications. Unlike user controls, these controls do not have an ASCX markup file, having all their code compiled into a dynamic link library (DLL) file.

User Control - User controls have their own events which are handled during the life of ASP.NET requests

HTML Controls ASP.NET Server Controls Validation Controls

ASP.NET CONTROLS FEATURES Automatic state management. Simple access to object values without

having to use the Request object. Ability to react to events in server-side code

to create applications that are better structured.

Common approach to building user interfaces for Web pages.

Output is automatically customized based on the capabilities of the browser.

HTML Controls

ASP.NET HTML CONTROLS

By default, HTML elements on an ASP.NET Web page are not available to the server; they are treated as opaque text that is passed through to the browser. However, by converting HTML elements to HTML server controls, you expose them as elements you can program in server-based code.

ASP.NET HTML CONTROLS

By default, HTML elements on a Web Forms page are not available to the server; they are treated as markup that is passed through to the browser. However, if you add an id attribute and the attribute runat="server”

ASP.NET recognizes the element as a control on the page and you can program it with server-based code. If you convert an HTML DIV element to an ASP.NET server control, it is created as an instance of the HtmlGenericControl class.

ANCHOR <html>

<body>

<form runat="server"><a id="link1" runat="server">Visit W3Schools!</a><br /><a id="link2" runat="server">Visit Microsoft!</a></form>

</body></html>

<script  runat="server">Sub Page_Load   link1.HRef="http://www.w3schools.com"   link1.Target="_blank"   link1.Title="W3Schools"

   link2.HRef="http://www.microsoft.com"   link2.Target="_blank"   link2.Title="Microsoft"End Sub

</script>

ASP.NET HTML CONTROLS - BUTTON <script  runat="server">

Sub button1(Source As Object, e As EventArgs)   p1.InnerHtml="You clicked the blue button!"End SubSub button2(Source As Object, e As EventArgs)   p1.InnerHtml="You clicked the pink button!"End Sub</script>

<html><body>

<form runat="server“> <button id="b1" OnServerClick="button1”style="background-

color:#e6e6fa;height:25;width:100" runat="server“>Blue button!</button>

<button id="b2“ OnServerClick="button2“ style="background-color:#fff0f5;height:25;width:100" runat="server“>Pink button!</button>

<p id="p1" runat="server" /></form> </body></html>

IMAGE HTML CONTROL <script  runat="server">

Sub Page_Load(Sender As Object,E As EventArgs)   image1.Src="smiley.gif"   image1.Alt="Smiley"   image1.Border="3"End Sub</script>

<html><body>

<form runat="server"><img id="image1" runat="server" /></form>

</body></html>

HTMLINPUTBUTTON CONTROL <script  runat="server">Sub submit(sender As Object, e as EventArgs)if name.value<>"" then   p1.InnerHtml="Welcome " & name.value & "!"end ifEnd Sub</script>

<html><body>

<form runat="server">Enter your name: <input id="name" type="text" size="30" runat="server" /><br /><br /><input type="submit" value="Submit" OnServerClick="submit" runat="server" /><p id="p1" runat="server" /></form>

</body></html>

HTMLInputCheckbox

<script  runat="server">Sub submit(Source As Object, e As EventArgs)if red.Checked=True then   p1.InnerHtml="You prefer red!"else   p1.InnerHtml="You prefer blue!"end ifred.checked=falseblue.checked=falseEnd Sub</script>

<html><body>

<form runat="server">What color do you prefer?<br /><input id="red" type="checkbox" runat="server" /> Red<br /><input id="blue" type="checkbox" runat="server" /> Blue<br /><input type="button" value="Submit" OnServerClick="submit" runat="server"/><p id="p1" runat="server" /></form>

</body></html>

HTMLInputRedioButton

<html><body>

<form runat="server"><p>Select your favorite color:<br /><input id="r1" name="col" type="radio" runat="server">Red</input><br /><input id="r2" name="col" type="radio" runat="server">Green</input><br /><input id="r3" name="col" type="radio" runat="server">Blue</input><br /><input type="button" value="Submit" OnServerClick="submit" runat="server"/><p id="p1" runat="server" /></form>

</body></html>

<script  runat="server">Sub submit(Source As Object, e As EventArgs)if r1.Checked=True then   p1.InnerHtml="Your favorite color is red"else   if r2.Checked=True then     p1.InnerHtml="Your favorite color is green"   else     if r3.Checked=True then       p1.InnerHtml="Your favorite color is blue"     end if   end ifend ifEnd Sub

HtmlAnchor Controls an <a> HTML elementHtmlButton Controls a <button> HTML elementHtmlForm Controls a <form> HTML element

HtmlGenericControls other HTML element not specified by a specific HTML server control, like <body>, <div>, <span>, etc.

HtmlImage Controls an <image> HTML element

HtmlInputButtonControls <input type="button">, <input type="submit">, and <input type="reset"> HTML elements

HtmlInputCheckBox

Controls an <input type="checkbox"> HTML element

HtmlInputFile Controls an <input type="file"> HTML elementHtmlInputHidden Controls an <input type="hidden"> HTML elementHtmlInputImage Controls an <input type="image"> HTML elementHtmlInputRadioButton

Controls an <input type="radio"> HTML element

HtmlInputTextControls <input type="text"> and <input type="password"> HTML elements

HtmlSelect Controls a <select> HTML elementHtmlTable Controls a <table> HTML elementHtmlTableCell Controls <td>and <th> HTML elementsHtmlTableRow Controls a <tr> HTML elementHtmlTextArea Controls a <textarea> HTML element

Server Controls

ASP.NET SERVER CONTROLS The HTML server controls are Hypertext Markup

Language (HTML) elements that include a runat=server attribute. The HTML server controls have the same HTML output and the same properties as their corresponding HTML tags.

HTML server controls provide automatic state management and server-side events.

The System.Web.UI.HtmlControls.HtmlControl base class contains all of the common properties. HTML server controls derive from this class.

ASP.NET does not require literal (not dynamic) HTML content to be well formed, but it does require that all HTML elements be properly closed (with either a trailing "/" or a closing tag) and cleanly nested (overlapping tags are not allowed). If HTML elements are not closed properly, ASP.NET will not recognize the element.

BUTTON SERVER CONTROL

<script  runat="server">Sub submit(Source As Object, e As EventArgs)   button1.Text="You clicked me!"End Sub</script>

<html><body>

<form runat="server"><asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" /></form>

</body></html>

ASP.NET SERVER CONTROLS ADV The HTML server controls map one to one with

their corresponding HTML tags. When the ASP.NET application is compiled, the

HTML server controls with the runat=server attribute are compiled into the assembly.

Most controls include an OnServerEvent for the most commonly used event for the control. For example, the <input type=button> control has an OnServerClick event.

The HTML tags that are not implemented as specific HTML server controls can still be used on the server side; however, they are added to the assembly as HtmlGenericControl.

When the ASP.NET page is reposted, the HTML server controls keep their values.

HtmlAnchor Controls an <a> HTML elementHtmlButton Controls a <button> HTML elementHtmlForm Controls a <form> HTML element

HtmlGenericControls other HTML element not specified by a specific HTML server control, like <body>, <div>, <span>, etc.

HtmlImage Controls an <image> HTML element

HtmlInputButtonControls <input type="button">, <input type="submit">, and <input type="reset"> HTML elements

HtmlInputCheckBox

Controls an <input type="checkbox"> HTML element

HtmlInputFile Controls an <input type="file"> HTML elementHtmlInputHidden Controls an <input type="hidden"> HTML elementHtmlInputImage Controls an <input type="image"> HTML elementHtmlInputRadioButton

Controls an <input type="radio"> HTML element

HtmlInputTextControls <input type="text"> and <input type="password"> HTML elements

HtmlSelect Controls a <select> HTML elementHtmlTable Controls a <table> HTML elementHtmlTableCell Controls <td>and <th> HTML elementsHtmlTableRow Controls a <tr> HTML elementHtmlTextArea Controls a <textarea> HTML element

<button type="button">Click Me!</button>HTML tag literal

<button id="b1" OnServerClick="button1”style="background-color:#e6e6fa;height:25;width:100" runat="server“>Blue button!</button>

HTML control

<asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" /> ASP.NET Server control

Validation Conrols

Validation server controls are a series of controls that help you validate the data that the user enters into the other controls that are provided with ASP.NET.

Client side form validation server side form validation

Validation server controls are the only type of ASP.NET server controls that also generate client-side script. All the other controls work with the idea of making postbacks to the server (a request to the server to get a response

six different validation server controls are available for ASP.NET: RequiredFieldValidator CompareValidator RangeValidator RegularExpressionValidator CustomValidator ValidationSummary

Validation Server Control Description

RequiredFieldValidatorEnsures that the user does not skip a form entry field

CompareValidator

Allows for comparisons between the user's input and another item using a comparison operator (equals, greater than, less than, and so on)

RangeValidator

Checks the user's input based upon a lower- and upper-level range of numbers or characters

RegularExpressionValidator

Checks that the user's entry matches a pattern defined by a regular expression. This is a good control to use to check e-mail addresses and phone numbers

CustomValidatorChecks the user's entry using custom-coded validation logic

ValidationSummary

Displays all the error messages from the validators in one specific spot on the page

NOT ALL BUTTON CLICKS ARE EQUAL

For instance, you might have a Cancel or Reset button on the Web page. If the user clicks one of these buttons, you don't want that button click to validate the contents contained in the Web form.

<asp:Button id="Button1" runat="server" Text="Button" CausesValidation="False"></asp:Button

REQUIREDFIELDVALIDATOR

The RequiredFieldValidator server control makes sure that the user enters something into the field that it is associated with in the form.

You need to tie the RequiredFieldValidator to each control that is a required field in the form.

<%@ Page Language="C#" %> <script runat="server"> void Button1_Click(Object sender, EventArgs e) { Label1.Text = "Page is valid!"; } </script>

<html> <head> </head> <body>

<form runat="server"> <p> <asp:TextBox id="TextBox1“ runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1"

runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>

</p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>

</p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>

EXECUTION As you run this simple page, notice a few things.

First of all, if you are running a client that is considered an upper-level browser (for example, Internet Explorer 4.0 or better), the code generated to perform the validation is client-side. To see this, right-click the page, and then click View Source. You see JavaScript in the code of the page.

The JavaScript in the code of the page means that the required field checking against the text box on the page is done client-side. To test this, simply click the button on the page, and you see the Required! error message displayed. Next, enter a value in the TextBox control, and then press TAB. The RequiredFieldValidator server control is then triggered.

MORE ATTRIBUTES

<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" BackColor="DarkGray" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" ForeColor="White" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Small">&nbsp;Enter something&nbsp; </asp:RequiredFieldValidator>

DOUBLE-CHECKING CLIENT-SIDE VALIDATION

One interesting point is that even though the form data is validated on the client (eliminating the need for additional requests to and responses from the server to validate the data), the data entered is re-verified on the server.

After the data is checked on the client and found valid, it is rechecked on the server using the same validation rules.

These are rules that you establish to ensure against some tricky programmer out there trying to bypass the validation process by posting the page to the server as if it passed validation.

USING THE INITIALVALUE PROPERTY WITH A TEXTBOX SERVER CONTROL

<asp:TextBox id="TextBox1" runat="server">Hello</asp:TextBox> &nbsp; <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please change value" ControlToValidate="TextBox1" InitialValue="Hello"> </asp:RequiredFieldValidator>

REQUIRING A VALUE CHANGE AND DISALLOWING EMPTY VALUES AT THE SAME TIME

<asp:TextBox id="TextBox1" runat="server">Hello</asp:TextBox> &nbsp; <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please change value" ControlToValidate="TextBox1" InitialValue="Hello"> </asp:RequiredFieldValidator>

<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Do not leave empty" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>

USING THE INITIALVALUE PROPERTY WITH A DROPDOWNLIST CONTROL

<asp:DropDownList id="DropDownList1" runat="server"> <asp:ListItem Selected="True">Select a profession</asp:ListItem> <asp:ListItem>Programmer</asp:ListItem> <asp:ListItem>Lawyer</asp:ListItem> <asp:ListItem>Doctor</asp:ListItem> <asp:ListItem>Artist</asp:ListItem> </asp:DropDownList> &nbsp;

<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please make a selection" ControlToValidate="DropDownList1" InitialValue="Select a profession"> </asp:RequiredFieldValidator>

THE COMPAREVALIDATOR CONTROLVALIDATING AGAINST OTHER CONTROLS ON THE WEB FORM

<asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage=“ not match!" ControlToValidate="TextBox2" ControlToCompare="TextBox1"></asp:CompareValidator>

WRITE PROGRAM

VALIDATING AGAINST CONSTANTS

Checking to make sure value entered is of a specific data type

Age: <asp:TextBox id="TextBox1" runat="server"

MaxLength="3"> </asp:TextBox> &nbsp; <asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="You must enter a number" ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck">

</asp:CompareValidator>

Comparing values against constants for validity

Age: <asp:TextBox id="TextBox1"

runat="server"></asp:TextBox> &nbsp; <asp:CompareValidator id="CompareValidator1" runat="server" Operator="GreaterThan" ValueToCompare="18" ControlToValidate="TextBox1" ErrorMessage="You must be older than 18 to join" Type="Integer"></asp:CompareValidator>

Operator =Equal ,,NotEqual ,GreaterThan ,GreaterThanEqual ,LessThan ,LessThanEqual ,DataTypeCheck

THE RANGEVALIDATOR CONTROL

Age: <asp:TextBox id="TextBox1"

runat="server"></asp:TextBox> &nbsp; <asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox1" Type="Integer" ErrorMessage="You must be between 30 and 40" MaximumValue="40" MinimumValue="30">

</asp:RangeValidator>

Type = String, Integer, Double, Date, and Currency

COMPARING AN ENTRY TO A RANGE OF CHARACTERS

Last name: <asp:TextBox id="TextBox1"

runat="server"> </asp:TextBox> &nbsp;

<asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Your last name needs to be between M and P" MaximumValue="Q" MinimumValue="M">

</asp:RangeValidator>

THE REGULAREXPRESSIONVALIDATOR CONTROL

Email: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;

<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="You must enter an email address" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>

USING IMAGES FOR YOUR VALIDATION MESSAGES

Email: <asp:TextBox id="TextBox1" runat="server">

</asp:TextBox> &nbsp; <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage='<img src="error.gif">'

ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>

THE CUSTOMVALIDATOR CONTROL

The CustomValidator server control enables you to develop your own custom server-side or client-side validations. At times, you may want to compare the user's input to a value in a database, or to determine whether his input conforms to some arithmetic validation that you are looking for (for instance, if the number is even or odd).

<html> <head> <script language="JavaScript"> function validateNumber(oSrc, args) { args.IsValid = (args.Value % 5 == 0); }

</script> </head> <body> <form runat="server"> <p> Number: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> &nbsp;

<asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Number must be divisible by 5" ClientValidationFunction="validateNumber"> </asp:CustomValidator> </p> <p>

<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button> </p> <p>

<asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>

<html> <head> </head> <body> <form runat="server"> <p> Number: <asp:TextBox id="TextBox1"

runat="server"></asp:TextBox> &nbsp; <asp:CustomValidator id="CustomValidator1"

runat="server" ControlToValidate="TextBox1" ErrorMessage="Number must be divisible by 5" OnServerValidate="ValidateNumber">

</asp:CustomValidator> </p> <p>

<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>

<%@ Page Language="C#" %>

<script runat="server">

void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid)

{

Label1.Text = "VALID ENTRY!"; }

}

void ValidateNumber(object source, ServerValidateEventArgs args)

{

try

{

int num = int.Parse(args.Value);

args.IsValid = ((num%5) == 0);

} catch(Exception ex) { args.IsValid = false; }

}

</script>

THE VALIDATIONSUMMARY CONTROL

The ValidationSummary server control works with all the validation server controls on the page. It takes all the error messages that the other validation controls send back to the page and puts them all in one spot (that you specify) on the page. These error messages can be displayed in a list, bulleted list, or paragraph.

PROGRAM VALIDATION_SUMMARY OUTPUT

MESSAGE BOX FOR ERROR INSTADE OF LIST

<asp:ValidationSummary id="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False"></asp:ValidationSummary>

CONCLUSION

Validation and Web controls make an outstanding combination for building smart forms.

Building databases

NET Framework data provider Description

.NET Framework Data Provider for SQL Server

Provides data access for Microsoft SQL Server version 7.0 or later. Uses the System.Data.SqlClient namespace.

.NET Framework Data Provider for OLE DB

For data sources exposed using OLE DB. Uses the System.Data.OleDb namespace.

.NET Framework Data Provider for ODBC

For data sources exposed using ODBC. Uses the System.Data.Odbc namespace.

.NET Framework Data Provider for Oracle

For Oracle data sources. The .NET Framework Data Provider for Oracle supports Oracle client software version 8.1.7 and later, and uses the System.Data.OracleClient namespace.

Core Objects of .NET Framework Data Providers

Object Description

Connection

Establishes a connection to a specific data source. A data adapter needs connection to a data source to read write data and it uses OleDbConnection, OdbcConnection, sqlConnection or oracleConnection object to communicate with a data source.

DataAdapter

Use to communicate between datasource and a dataset. OleDbDataAddapter, OdbcDataAddapter, sqlDataAddapter or oracleDataAddapter, AccessDataAdapter

Command

Data adapter are used to read , add ,update and delete records in data source.Data adapter contains command objects which specifies how this works. SelectCommand,InsertCommand, UpdateCommand , DeleteCommand

DataSetA dataset is the local repository. (Record set)

Object Description

DataTables DataRowDataColomuns

Holds data table from datasource.

DataView

Subset of data from DataTable. You can use dataview for various operations like datasorting, filtring,searching

DataRelational Use to relate two data tables trough DataColumn object

DATA SOURCE CONTROLS

AccessDataSource Control ObjectDataSource Control XMLDataSource Control SQLDataSource Control

DATA BOUND CONTROL

GridView FormView DetailsView Repeater DataList

ACCESSDATASOURCE CONTROL

- Retrieves data from access database(.mdb)- Associates them to bound controls to display- DataFile requiers path of .mdb file

OBJECTDATASOURCE CONTROL

Provides data access to a business object or classes that return data and create web application on multi-tier architecture.

Combined with data bound objects

The ObjectDataSource serves as a proxy for working with some other object. To configure the ObjectDataSource we specify this underlying object and how its methods map to the ObjectDataSource's Select, Insert, Update, and Delete methods.

Once this underlying object has been specified and its methods mapped to the ObjectDataSource's, we can then bind the ObjectDataSource to a data Web control.

Accessing and displaying data from a Business Logic Layer can be accomplished without writing a line of code thanks to ASP.NET 2.0's ObjectDataSource control.

The ObjectDataSource invokes a specified method of a class and returns the results. These results can be displayed in a data Web control that's bound to the ObjectDataSource