asp net rina zviel girshin lecture 3 n.
Skip this Video
Loading SlideShow in 5 Seconds..
ASP.NET Rina Zviel-Girshin Lecture 3 PowerPoint Presentation
Download Presentation
ASP.NET Rina Zviel-Girshin Lecture 3

Loading in 2 Seconds...

play fullscreen
1 / 42

ASP.NET Rina Zviel-Girshin Lecture 3 - PowerPoint PPT Presentation

  • Uploaded on

ASP.NET Rina Zviel-Girshin Lecture 3. Overview. Cookies Validation controls Client and server side validation Validation control examples. Cookie. HTTP protocol is stateless – does not remember users or user’s actions.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

ASP.NET Rina Zviel-Girshin Lecture 3

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
    Presentation Transcript
    1. ASP.NET Rina Zviel-Girshin Lecture 3

    2. Overview • Cookies • Validation controls • Client and server side validation • Validation control examples

    3. Cookie • HTTP protocol is stateless – does not remember users or user’s actions. • Cookie is a small file embedded by server application on the user's computer. • The file is a text file, usually stored in directory named Cookies and having username@WebServerName[1].txt name. • Cookies are useful for storing nonessential data • user preferences or choices. • Each time the same client requests a page the cookie is sent to the server. • The server checks cookie's value and perform some actions according to information stored in cookie.

    4. Cookies in ASP.NET • Exists class HttpCookie which provides a type-safe way to create and manipulate individual HTTP cookies. • Exist several constructors. • A one argument constructor creates a cookie with a given name. • The object of the class has several properties. Some of those are: • Expires- gets or sets the expiration date and time for the cookie. • Values - gets a collection of key-and-value pairs that are contained within a single cookie object. Items can be added to the collection using add(key,value) method. • Value - gets or sets an individual cookie value.

    5. Example- cookietest1.aspx <%@ Page language="c#" Codebehind="cookietest1.aspx.cs" Inherits="cookie1.WebForm1" %> <html><head><title>WebForm1</title></head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:Label id="Label1" runat="server" Width="303px" Height="23px">Choose the language</asp:Label> <asp:Button id="Button1" runat="server" Width="184px" Height="53px" Text="Remember"></asp:Button> <asp:RadioButtonList id="RadioButtonList1" runat="server" Width="277px" Height="56px"> <asp:ListItem Value="VB" Selected="True">VB</asp:ListItem> <asp:ListItem Value="CSharp">C#</asp:ListItem> </asp:RadioButtonList> </form></body></html>

    6. Output Label RadioButtonList Button

    7. Codebehind- cookietest1.aspx.cs using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace cookie1 { public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.RadioButtonList RadioButtonList1; protected System.Web.UI.WebControls.Label Label1;

    8. Codebehind- cookietest1.aspx.cs (2) private void Button1_Click(object sender, System.EventArgs e){ if (Request.Cookies["language"] == null) { HttpCookie cookie = new HttpCookie("language"); cookie.Expires = DateTime.MaxValue; // never expires cookie.Value = RadioButtonList1.SelectedItem.Value; Response.Cookies.Add(cookie); //sends cookie to user Button1.Text="Show cookie"; } else { String str =Request.Cookies["language"].Value; Label1.Text="All the examples will be shown using "+str; RadioButtonList1.Visible=false; Button1.Visible=false; } } } //end of class }//end of namespace

    9. Output

    10. Output from cookie else { String str = Request.Cookies["language"].Value; Label1.Text="All the examples will be shown using " +str; RadioButtonList1.Visible=false; Button1.Visible=false; }

    11. Validation • Validation definitions: • Tests to determine whether an implemented system fulfills its requirements. • The checking of data for correctness or for compliance with applicable standards, rules, and or minimum requirements. • ASP.NET provides sophisticated validation mechanism that can be added to any page. • What do we want to validate? • Usually a page data items entered or changed by the user.

    12. Validation process • Validation can be performed on client’s side or on server’s side or both. • A client-side validation requires • writing a special script to check if user’s data is correct. • A server-side validation requires • or writing a special server script to check the data • or usage of the specially developed validation server controls. • A good technique is to use both.

    13. Client-side validation • Reduces the number of round trips necessary, instant feedback to the user. • With a client-side validation errors are detected on the client side when the form is submitted to the server. • If any of the validators are found to be in error, the submission of the form to the server is cancelled and the validator's Text property is displayed. • This permits the user to correct the input before submitting the form to the server. • Written inside some script. • Can be viewed by malicious user to enter bad data. • Some browser can’t perform a required script.

    14. Server-side validators • Written inside a server script or server validation controls are used. • Information hiding, security and more. • Functions correctly in any browser (does not depend on client side - performed on server). • A server validation control is used to validate the data written of some input control. • The validation process is relatively simple • If the data does not pass validation, it will display an error message to the user. • If the data passes validation continue to the next item/page/action.

    15. ASP.NET Validation Controls • ASP.NET validation controls automatically generate client-side and server-side code. • If a browser supports a client script language then a client-side validation script is sent to the browser. • If a browser incapable of supporting a client script language then a server validation script automatically implemented. • You can enable/disable client-side validation: • Client-side validation is enabled by default.”uplevel” validation. • <%Page ClientTarget=“downlevel” %> -disables client-side validation

    16. Adding Validation Control to the Page • Validation controls are added to a Web Forms page like any other server controls. • Exists several types of Validation controls: • such as range checking or pattern matching, • or a RequiredFieldValidator that ensures that a user does not skip this field. • You can attach more than one validation control to one input control. • For example • you might specify both that an entry is required and that it must contain a specific range of values.

    17. Input to validate • Validation controls work with a limited subset of HTML and Web server controls. • For each control, a specific property contains the value to be validated. • Some input controls and their validation property: • HtmlInputText (Value) HtmlTextArea(Value) HtmlSelect(Value) HtmlInputFile(Value) – where HTML means HTML control • TextBox(Text) ListBox(SelectedItem.Value) DropDownList (SelectedItem.Value) RadioButtonList (SelectedItem.Value) HTML controls Web-server controls

    18. Types of Validation Controls • There are 5 types of individual validation controls in ASP.NET: • RequiredFieldValidator • CompareValidator • RangeValidator • RegularExpressionValidator • CustomValidator • Also exists a ValidationSummary control that gathers all ErrorMessages and displays them using a bulleted list, a plain list or a single paragraph format. • Each control has a specific action to perform.

    19. Syntax • A basic syntax for creating a validation control is: <asp:control_name id="some_id" ControlToValidate ="some_cnt" runat="server" /> • A more complex syntax specifies more properties: <asp:control_name id="some_id" ControlToValidate ="some_cnt" Display=“value” Text=“some text” ErrorMessage=“message” runat="server" /> • Display property values can be: • static (default - may be hidden but requires a span display), • dynamic (span with none or inline display) and • none (no error message).

    20. RequiredFieldValidator • A RequiredFieldValidatoris the simplest form of validation. • It makes some input a required field - ensures that the user does not skip this entry. • If the user enters any value in a field (even gibberish) it is valid. • The validation fails if the input value does not change from its initial value (InitialValueproperty). • By default the InitialValue is an empty string (""). • If all of the fields in the page are valid, the page is valid.

    21. Example <html><body><form runat="server">Name: <asp:TextBox id="name" runat="server" /><br />Age: <asp:TextBox id="age" runat="server" /><br /><br /><asp:Button runat="server" Text="Submit" /><br /><br /><asp:RequiredFieldValidator ControlToValidate="name"Text="The name field is required!“ runat="server" /></form></body></html>

    22. RangeValidator • ARangeValidator control is used to check that the user enters an input value that falls between two values (a given range). • It is possible to check ranges within • numbers, dates and characters. • ControlToValidate contains name of the control to be validated. • MinimumValue and MaximumValuedefine the minimum and maximum values of the valid range. • Type property specifies the data type of the value to check. • Currency, Date/Time, Double, Integer or String.

    23. Example <html><body><form runat="server">Enter a date between 2005-01-01 and 2005-12-31:<br /><asp:TextBox id="tb" runat="server" /><br /><br /><asp:Button Text="Submit" runat="server" /><br /><br /><asp:RangeValidator ControlToValidate="tb"MinimumValue="2005-01-01" MaximumValue="2005-12-31"Type="Date" EnableClientScript="false"Text="The date must be between 2005-01-01 and 2005-12-31!"runat="server" /></form></body></html>

    24. CompareValidator • Compares the value of one input control to the value of another input control or to a fixed value. • A CompareValidator uses three key properties to perform its validation. • ControlToValidate and ControlToCompare (or ValueToCompare) containing the values to compare • Operator defines the type of comparison to perform • for example: Equal or Not Equal, LessThan or GreaterThanEqual • A Type property of the control is defined as in RangeValidator. • If the expression evaluates true, the validation result is valid.

    25. Example <html><body><form runat="server"><table border="0" bgcolor="#b0c4de">   <tr valign="top"><td colspan="4"><h4>Compare two values</h4></td> </tr><tr valign="top"> <td><asp:TextBox id="txt1" runat="server"/></td>  <td> = </td> <td><asp:TextBox id="txt2" runat="server"/> </td> <td><asp:Button Text="Validate" runat="server" /></td>  </tr></table><br /><asp:CompareValidator id="compval“ Display="dynamic"ControlToValidate="txt1“ ControlToCompare="txt2" ForeColor="red“ BackColor="yellow" Type="String“ EnableClientScript="false" Text="Validation Failed!" runat="server" /></form></body></html> Why no operator = value given? STYLE

    26. Output ForeColor="red“ BackColor="yellow" Text="Validation Failed!"

    27. Example: a fix value validation <%@ Page Language="C#"%> <script runat=“server”> void Button_Click(Object sender, EventArgs e) {Response.Redirect( "ThankYou.aspx" );} </script> <html><body><form Runat="Server"> Minimum Bid: $2,000<br/> Enter your bid: <asp:TextBox id="Amount" Columns="8" Runat="Server"/> <asp:CompareValidator ControlToValidate="Amount" ValueToCompare="2,000" Display="Dynamic" Text="Your bid must be greater than the minimum bid!" Operator="GreaterThan" Type="Currency" Runat="Server" /> <p><asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form></body></html>

    28. CustomValidator • Allows you to write a method to handle the validation of the value entered • calls a user-defined function to perform validations. • A user defined function can be executed in the server or in client-side script. • OnServerValidate property specifies the name of the server-side validation script function to be executed. • ClientValidationFunction property specifies the name of the client-side validation script function to be executed • type FunctionName (source, arguments)

    29. Example a spaghetti-like code <script  runat="server">void user(object source, ServerValidateEventArgs args )  { if (args.Value.length<8 || args.Value.length>18)     args.IsValid=false    else args.IsValid=true   }</script> <html><body><form runat="server"><asp:Label runat="server" Text="Enter a username: " /><asp:TextBox id="txt1" runat="server" /><asp:Button Text="Submit" runat="server"/><br /><asp:CustomValidator ControlToValidate="txt1"OnServerValidate="user" Text="A username must be between 8 and 18 characters!" runat="server"/> </form></body></html>

    30. Output

    31. RegularExpressionValidator • A RegularExpressionValidator control is used to ensure that an input value matches a specified pattern, called a regular expression. • Both server- and client-side validation are performed unless • the browser does not support the client-side validation • or the EnableClientScript property is set to false. • ValidationExpression property specifies the expression used to validate an input control. • The regular expression is a string and therefore is written between quotes.

    32. Regular Expressions • Some basic regular expressions: • "[a-z]" validates all characters of the alphabet • "[^a-z]" validates all characters that is not in the alphabet • “[abcd]” a “character class” - means a or b or c or d • “.” means any character except a newline • “r*” - means repetition of r 0 or more times • “a?” means zero or one a’s • "[0-9]" validates all numeric characters • "[^0-9]" valid all non-numeric characters • "\d" validates a numeric character

    33. Regular Expressions cont. • Some basic regular expressions: • "\n" validates a line break • "\t" validates a tabulation • "\s" validates all blank character (line break, space, tabulation) • "\." is for displaying the point • "^" is for being at the beginning of the line • "$" is for being at the end of the line (so "^$" is an empty string) • “a{1,3}” - means from one to three a’s • “rs” – means r concatenated with s

    34. Examples • “[1-9][0-9]*” validates integer constants  • “[^0-9\n]” validates any letter except upper case letters or a new-line • "zo{2}" validates "zoo“ • "zo*" validates "z“, “zo” and "zoo" (one character followed by * is valid if this character is present 0 or n times) • "zo{1,2}" validates "zo" and "zoo“ • "do(es)?" validates "do" or "does"

    35. More complicated expressions • An email validation (pattern : • ".*@.*\..*" • A five digits postal code will be validated by • "^\d{5}$“ • A phone number will be validated by (bezeq) • "^0[2-48-9]-\d{7}$"

    36. Partial Example Enter an email: <input type="text" id=“email" size="40" runat="server" />Tip: enter a valid email address<asp:RegularExpressionValidator id="valRegExpr" ControlToValidate=“email“ runat="server"ValidationExpression=".*@.*\..*"ErrorMessage="* Your entry does not match the correct email syntax“ Display="dynamic">* </asp:RegularExpressionValidator>

    37. IsValid property • After all validation controls have been processed, the IsValid property on the page is set. • If any of the controls shows that a validation check failed, the entire page is set to be invalid. • If a validation control is in error, an error message may be displayed in the page by that validation control or in a ValidationSummary control elsewhere on the page. • The ValidationSummary control is displayed when the IsValid property of the page is false.

    38. ValidationSummary • The ValidationSummary control is used to display a summary of all validation errors occurred in a Web page. • The error message displayed in this control is specified by the ErrorMessage property of each validation control. • If an ErrorMessage property of the validation control is not set - no error message is displayed for that validation control. • DisplayMode property can be one of the • BulletList, List or SingleParagraph

    39. Example <html><body><form runat="server"><table><tr><td><table bgcolor="#b0c4de" cellspacing="10"> <tr>  <td align="right">Name:</td> <td><asp:TextBox id=“tb" runat="server"/></td>  <td> <asp:RequiredFieldValidator Text="*"      ControlToValidate=“tb"   ErrorMessage="Name“ runat="server"/> </td> </tr>   <tr> <td align="right">Card Type:</td>  <td><asp:RadioButtonList id="rbl" RepeatLayout="Flow“ runat="server">    <asp:ListItem>Diners</asp:ListItem><asp:ListItem>MasterCard</asp:ListItem>  </asp:RadioButtonList></td>   <td> <asp:RequiredFieldValidator ControlToValidate="rbl" InitialValue=" " ErrorMessage="Card Type" Text="*"    runat="server"/> </td> </tr>   <tr> <td></td>  <td><asp:Button id="b1" Text="Submit“ runat="server"/> </td> <td></td> </tr></table> <asp:ValidationSummaryHeaderText="You must enter a value in the following fields:"DisplayMode="BulletList“ EnableClientScript="true“ runat="server"/></form></body></html>

    40. Output <asp:ValidationSummaryHeaderText="You must enter a value in the following fields:"DisplayMode="BulletList“ EnableClientScript="true“ runat="server"/>

    41. Events in .NET • There are hundreds events in .NET. • Some are user depended • clicks, selections, changing values, • and some are generated by ASP.NET itself • database item inserted into DataGrid. • The user depended events can be divided into two types: • Postback Events - immediately reported to the Web server via a form submission • buttons, hyperlinks • Non-Postback Events - the browser takes note of but doesn't report until the next form submission • checkbox, radio button and list selections, text entries

    42. Any Questions?