62
ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0 Chapter 2 Introduction to Programming

Embed Size (px)

Citation preview

Page 1: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0

Chapter 2Introduction to Programming

Page 2: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 2

Objectives

Page 3: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 3

Integrate Programming and Web Forms

• The Web Form is a web page that can contain:– HTML controls (<p>)– Client-side scripts including JavaScript– ASP.NET controls – these run on the web server and are

rendered as HTML and JavaScript on the client• HTML server (<p runat=“server” id=“P1”></p>• Web server controls (<asp:calendar runat=“server”

id=“Calendar1” />• Controls can be written manually or user can use the visual

tools to add them to the Web Form

Page 4: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 4

Integrate Programming and Web Forms (continued)

• Compiled server programs – Inline in the page using <% %> delimiters– Embedded

• Usually at the top of the page with <script> tags • Set the runat=“server” property • Change the language to VB

– Code behind the page• Filename has the extension .aspx.vb• Separating server programming and Web Forms allows you

to alter your presentation tier without interfering with how the page is processed by the business programming code

Page 5: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 5

Configure the Page Directive

• Set the default page-level properties– Default Language property set to VB indicates the

code behind the page is written in Visual Basic .NET<%@ Page Language="VB" %>

– File location is identified by the CodeFile property– Inherits property indicates that the code behind the

page inherits the partial class<%@ Page Language="VB" CodeFile="Login.aspx.vb"

Inherits="Login" title=" Login Page" AutoEventWireup="false" %>

Page 6: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 6

Where to Place Your Programming Statements

• Only server controls interact with the code behind the page (web server and HTML server controls)– Must set the ID property

– Must set the runat=“server” property

– Line continuation character is the underscore – Do not break strings across lines

• Concatenate strings with & or +

Page 7: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 7

Using Variables and Constants in a Web Form

• Variable declaration – Declaration keywords define what parts of the web

application will have access to the variable– Variable name refers to the name of the variable as

well as a section of memory in the computer– Data type identifies what kind of data the variable

can store such as integer or string of characters– Multiple variables declare on a separate line, or use

a single line– Declare variables before used

• Explicit property of the Page directive configures the page to require you to declare all variables before use

Page 8: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 8

Declaring a Variable

• Declaring a variable is the process of reserving the memory space for the variable before it is used in the program

• Scope identifies what context the application can access the variable– Where your web application defines the variable determines

where the variable can be used within the application

• Local variables – Defined within a procedure – Used only where they were declared– Persist in memory while the procedure is being executed– More readable, easier to maintain, require less memory– Choose local variables unless multiple procedures require

them

Page 9: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 9

Declaring a Variable (continued)

• Module-level variables – Defined in the class but outside the procedures– Used by any procedures in the page– Not available to other Web Forms – Any procedure within the page can set or use value – Reserve memory space before it is used – When page loads, memory allocated and a value

assigned– After page unloads, memory can be reallocated

Page 10: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 10

Declaring a Variable (continued)

• Keywords specify the scope of the variable– Dim: With no other keyword, its use will mean the

variable is public– Public: Defines variable global or public, available

outside the Web Form– Friend: Defines variables used only within the

current web application or project– Protected: Defines variables used only by the

procedure where declared

Page 11: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 11

Declaring a Variable (continued)

• Variable Names– Cannot use any of the Visual Basic .NET commands

or keywords as your variable name – Must begin with a letter– Cannot use a period or space within a variable name– Avoid any special characters in a variable name

except for the underscore– Store values in variables using the assignment

operator, which is the equal sign (=)Dim CompanyName As String = "Barkley Builders"

Page 12: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 12

Declaring Constants

• Assign a value that does not change– Tax rates– Shipping fees– Mathematical equations

• Const keyword is used to declare a constant

• Naming rules for variables also apply

• Usually all uppercase

• Must assign the value when you declare the constantConst TAXRATE As Integer = 8

Page 13: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 13

Working with Different Data Types

• Text and Strings

• Numeric

• Date

• Boolean – True -1– False 0

Page 14: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 14

Working with Text Data

• Character text stored in strings and chars– Char data type stores a single text value as a number

between 0 and 65,535 – String data type stores one or more text characters

• Social Security numbers, zip codes, and phone numbers • Numbers stored as text strings are explicitly converted to

numerical data before using in an arithmetic expression

• Assign a string a value; the value must be within quotation marks

• Stored as Unicode and variable in length

Page 15: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 15

Strings

• Modify string using methods of the String object– Replace – replaces one string with another

• Concatenation joins one or more stringsDim ContactEmail As String = CompanyEmail.ToString()

& "<br />"

– Plus sign (+) represents the addition operator for mathematical equations and is used with non-strings; technically can be used instead of &, but it is not recommended

Page 16: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 16

Working with Numeric Data

• Data Types– Byte – integer between 0 and 255 stored in a single byte – Short – 16-bit number from –32,768 to 32,767; uses two bytes – Integer – 32-bit whole number; uses four bytes – Long – 64-bit number; uses eight bytes – Single – single-precision floating point (decimal); uses four bytes – Double – larger decimal numbers; requires eight bytes– Decimal – up to 28 decimal places; used to store currency

• Mathematical methods – Such as Floor, Ceiling, Min, and Max, Sqrt, Round, Truncate – Add, Equals, Divide, Multiply, and Subtract – Can use arithmetic operators (such as + = / * - )

Page 17: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 17

Working with Numeric Data (continued)

• System.String.Format method• Predefined Formats

– Number (N) is used to format the number using commas– Currency (C or c) will insert the dollar symbol and two decimals– Percent (P) will format the number as a percent– Fixed number (F or f) represents a fixed number with two

decimalsSystem.String.Format("{0:C}", 1234.45) String.Format("{0:P}", 1234.45)Format("Percent", 1234.45)

• User-defined format style with a mask – 0 to represent a digit, pound (#) to represent a digit or space – 1,231 and $24.99 and 5.54%

Format(1231.08, "#,###")Format(24.99, "$#,###.##") Format(0.0554, "0.00%")

Page 18: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 18

Working with Date and Time

• System.DateTime enclosed within a pair of pound signsDim MyBirthday As DateTimeMyBirthday = #3/22/2008#

• Local time – MyBirthday.UtcNow – UCT is Coordinated Universal Time (Greenwich Mean Time-

GMT)• String.Format

– d and D masks short and long date formats– t or T masks short and long time formats

Dim ShippingDate As DateTime = #3/12/2008#Format(ShippingDate, "d")

• User-defined format style with a mask Format(MyDT, "m/d/yyyy H:mm") 9/9/2007 17:34

Page 19: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 19

Converting Data Types

• System.Convert class • CInt function to convert string – CInt(strVariable)• Narrowing conversions

– Convert a decimal to an integer; you may lose some data– Convert 23.50 to 23; you lose the .50– Overflow exception is thrown – Not allowed by default because data could be lost – Convert 23.00 to 23; no data is lost, the .00 digits are not significant

and no exception is thrown• Widening conversion

– Convert 25 to 25.00; no data is lost– Allowed because no data loss occurs

• Set the Strict property of the Page directive to True to stop narrowing conversion that would result in data loss – Convert data types explicitly when narrowing conversions occur

Page 20: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 20

Working with Web Collections

• Each item in the collection is also referred to as an element– A collection is like a movie theatre – both containers– Refer to the movie theatre as a whole or to an individual seat – Each seat has its own number to locate the seat

• Items in the collection can be any valid data type such as a string or an integer, an object, or even another collection

• Used to decrease processing every time the web application had to retrieve the list

• The Systems.Collections namespace defines collections including the ArrayList, HashTable, SortedList, Queue, and Stack

Page 21: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 21

The ArrayList

• Create an ArrayListDim StateAbbrev As New ArrayListStateAbbrev.Add("IL")StateAbbrev.Add("MI")StateAbbrev.Add("IN")

• Modify ArrayList itemsStateAbbrev.Insert(0, "OK")StateAbbrev.Remove("OK")

• Iterate through the listDim iPos as IntegeriPos = StateAbbrev.IndexOf("OK")Dim MyCount As Integer MyCount = StateAbbrev.CountFor I = 0 to MyCount -1 MyStates.Text = StateAbbrev(I) & "<br />"Next

Page 22: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 22

The HashTable

• HashTable creates index of items using an alphanumeric key like an encyclopedia

• Modify ArrayList itemsDim HT1 As New HashTable()HT1.Add("1", "Mrs. Marijean Richards")HT1.Add("2", "1160 Romona Rd")HT1.Add("3", "Wilmette")HT1.Add("4", "Illinois")HT1.Add("5", "60093")

• Iterate through the list Dim CustomerLabel as StringFor each Customer in HT1 CustomerLabel &= Customer.Value & "<br />"Next Customer

Page 23: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 23

Working with Web Objects to Store Data

• HTTP protocols – send and receive data • Data is transmitted in the header in the data packet

– Date and time– Type of request (Get or Post)– Page requested (URL) – HTTP version – Default language– Referring page – IP address of the client– Cookies associated with that domain– User agent – used to identify the client software– Can add custom data fields

• Programmatically access the information that is transferred with the request and response using various programming objects

Page 24: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 24

Using the Request Object to Retrieve Data from the Header

• HTTP collects and stores the values as a collection of server variables– Request object of the Page class retrieves data sent by the browser – Server variables can be retrieved by using an HTTPRequest object with

Request.ServerVariables("VARIABLE_NAME")– Always in uppercase

• System.Web.HttpRequest class mapped to Request property of Page object– Use Page.Request.PropertyName or Request.PropertyName

Request.Url, Request.UserHostAddress, Request.PhysicalPath, Request.UrlReferrer.Host

• User agent provides a string to detect the browser version– JavaScript – string parsed to locate browser application name and

version• System.Web.HttpBrowserCapabilities class detects specific features

directly Dim MyBrowser as String = Request.Browser.Browser & "<br />" & _Request.Browser.Type & "<br />" & Request.Browser.Version & "<br />" & _

Request.Browser.Platform

Page 25: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 25

Using the Request Object to Retrieve Data from the Header (continued)

• Request object to retrieve form data from the header– Form collection – QueryString collection

• If Form method is Get, results are HTML encoded and appended with a question mark to the URL requested as a single string called the QueryString

www.course.com/index.aspx?CompanyName=Green%20River&Industry=Electronics

• Value is retrieved and assigned to a Label controlLabel1.Text = Request.QueryString("CompanyName")

Page 26: ASP.NET 2.0 Chapter 2 Introduction to Programming

Using the Request Object to Retrieve Data from the Header (continued)

• QueryString – Only valid URL characters, has a fixed limit length, and not appropriate

to send sensitive or personal information– URL will not support spaces and special characters– Manually encode and decode a string using:[R2

Server.UrlEncode(“The String”)[Server.UrlDecode(“The%20String”)

• List of System.Web.HttpRequest variables and properties view Quickstart Class Browser at www.asp.net/QuickStart/util/classbrowser.aspx

ASP.NET 2.0, Third Edition 26

Page 27: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 27

Accessing From Field Data

• Access the value properties of the form field directly for Server controls– Property name varies– CompanyName.Value

• Cross-page posting sends data from one form to another by setting the PostBackUrl property of an ImageButton, LinkButton, or Button control to the new page

• Detect if the user came from another page by determining if the Page.Previous property is null

Page 28: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 28

Working with the Response Object

• Response object is mapped to System.Web.HttpResponse class– All data sent is sent via the HttpResponse class or via the Response

object – IP address of the server and the name and version number of the web

server software – Cookies collection sends cookies that are written by the browser in a

cookie file – Status code indicates the browser request was successful or any error – Access status codes with a custom error message page

• Methods– WriteFile method sends entire contents of a text file to the web page– Write method sends a string to the browser including text, HTML tags,

and client script Dim strMessage as String = "Green River Electronics<br/>" Response.Write(strMessage)

Page 29: ASP.NET 2.0 Chapter 2 Introduction to Programming

Working with the Response Object (continued)

• Response object redirects the browser to another page with server-side redirection

• Visitor never knows that he or she has been redirected to a new page

• Browser is redirected using the HTTP headers Response.Redirect("http://www.course.com/")

• Keep the ViewState information, and insert true as the second parameterServer.Transfer("Page2.aspx", true)

ASP.NET 2.0, Third Edition 29

Page 30: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 30

Session Objects

• Session object maintains session state across a single user’s session– Session variables stored in the server’s memory accessed only

within the session – Cannot change the value and stored in a special session

cookie – Cannot track across multiple sessions– SessionID is a unique identifier determined by several factors,

including the current date and IP addresses of the client and server

Session("Session ID") = Session.SessionID

Session("Number") = Session.Count.ToString

Session.Timeout = "30"

Page 31: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 31

Session Objects (continued)

• Application variables are released from memory when web application is stopped, web server is stopped, or when the server is stopped Session("Member ID") = TextBox1.TextSession("Date of visit") = DateTime.Now.ToShortDateString Session("URL requested") = Request.Url.ToStringSession("Server") = _ Request.ServerVariables("SERVER_NAME").ToString

• Save state information in session variables or in __VIEWSTATE – ViewState – persisted across browser requests stored with HTML code

only about the server controls– Serialized into a base64-encoded data string and not encrypted and

can be viewedViewState("Publisher") = "Course Technology"

– Retrieve the value Dim MyPublisher As String = CStr(ViewState("Publisher"))

Page 32: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 32

Design .NET Web Applications

• Windows and Web Applications are different– Web application used in a browser or an Internet-

enabled device– Visual Basic .NET is a programming language

• ASP.NET is technology used to develop dynamic web applications within the .NET Framework– .NET Framework consists of a common language

runtime (CLR) and a hierarchical set of base class libraries

• A class is a named logical grouping of code• Class definition contains the functions, methods, and

properties that belong to that class

Page 33: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 33

Web Applications Architecture

Page 34: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 34

Organization of Classes in the .NET Framework

• Base class libraries are groups of commonly used built-in classes stored in executable files– Accessed from any .NET application– Contain fundamental code structures and methods

to communicate with system and applications – Organized in hierarchical logical groups called

namespaces• System namespace is at the top of the namespace

hierarchy, and all built-in classes inherit from it– Web controls located within the

System.Web.UI.Control.WebControl namespace

Page 35: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 35

Programming with Visual Basic .NET

• Linear programming – executed sequentially in a single file

• Procedural programming – used decision control structures, functions, and procedures to control the execution order – Decision control structures used conditional

expressions to determine which block of code to execute

• Object-oriented programming (OOP) – methods stored in classes can be reused throughout your web application

Page 36: ASP.NET 2.0 Chapter 2 Introduction to Programming

Event Driven Programming

• This is an extension of OOP

• The ‘main’ program sets up a collection of ‘listeners’

• When something happens in the environment, an appropriate listener is informed

• This usually means that a particular procedure or function is called

CBS 5/12/08 36

Page 37: ASP.NET 2.0 Chapter 2 Introduction to Programming

Model-View-Controller

• Architecture of an interactive system

• MVC– Model is the collection of objects representing the

data and the processing logic for that data– View is the collection of objects that make the visible

interface– Controller is the collection of objects that responds to

user interaction

• When we create classes it will almost always be in the Model– Exception: frame classes are implicitly created for us

CBS 5/12/08 37

Page 38: ASP.NET 2.0 Chapter 2 Introduction to Programming

Creating a Class

• The source file for the class ends in .vb, placed in a directory named App_Code

Public Class MyClass Private CompanyName As String = "Green River Electronics“

ASP.NET 2.0, Third Edition 38

Page 39: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 39

Using a Class in ASP.NET

• Create an instance of the class– Instantiation is the process of declaring and initializing an

object from a class • Use the class – need to import on the first line in the

code behind the pageImports MyClass()

Page 40: ASP.NET 2.0 Chapter 2 Introduction to Programming

Using a Class

• Declare a variable to store the object, and New to identify that this is an object based on a class definition

• In the class in the sample code below, the MyNewClass object is based on the MyClass class Dim MyNewClass As New GreenRiverWeb.MyClass()

• New object can access all of the variables, properties, functions, and procedures defined within MyClass Label1.Text = MyNewClass.CompanyName

ASP.NET 2.0, Third Edition 40

Page 41: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 41

Using a Procedure

• Procedures contain one or more programming statements and are executed when called by another procedure or when an event occurs (event procedure)– Pass zero or more arguments, called parameters, in a comma

delimited list and data type

• Subprocedure can be called from other locations and reused– Subprocedures do not return values – Cannot be used in an expression value – Declared using the keyword Sub– Exit Sub statement to stop the subprocedure

Page 42: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 42

Creating Subprocedures

• Example Note use _ to split lines)Sub SubprocedureName(CompanyName As String, _

TotalEmployees As Integer)

Programming statements go here

End Sub

• Call the subprocedure[Call] SubprocedureName("Green River Electronics",

3400)

Page 43: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 43

Creating Event Procedures

• Event procedure is attached to an object with events

• Not executed until triggered by an event

• Event handler intercepts an event

• An underscore (_) is used to separate the object name and the event nameSub objectName_event(Sender As Object, _

e As EventArgs)

Programming statements go here

End Sub

Page 44: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 44

Page Events

• Page lifecycle and events occur in order– Can intercept event handlers within event procedure – Page_Init – initializes the page framework hierarchy,

creates controls, deserializes the ViewState, and applies the previous settings to the controls

– Page_Load – loads Server controls into memory • Determine if the page has previously been loaded • Page.IsPostback property

– Page_PreRender – immediately before control hierarchy is rendered

– Page_Unload – page is removed from the memory

Page 45: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 45

Creating Functions

• Function is a block of code that is grouped into a named unit– Built-in functions .NET Framework – mathematical, date and time, string,

and formatting functions or create your own function with a unique name – End Function statement identifies the end of the function– Leave the function with Exit Function statement– Returns one value using the Return statement (same data type) Public Function GetDiscount(CustomerState As String) As IntegerDim MyDiscount as IntegerIf CustomerState = "MI" then

MyDiscount = 10Else

MyDiscount = 5End IfReturn MyDiscountEnd Function

• Parameter and data type passed when you call the function Dim MembershipFee As IntegerMembershipFee = 100 - GetDiscount("MI")

Page 46: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 46

Creating a Property Method

• Property method sets value of a variable defined in an object– Used to expose private variables defined within the class – All new objects inherit same properties as the original

Public ReadOnly Property StoreName() As String

Get

Return StoreName

End Get

End Property

• Retrieve property lblContact.Text = ch2_classname.StoreName.ToString()

Page 47: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 47

Programming Control Structure

• Control statements determine both whether and how an action statement is executed, and the order – Decision control structures alter the execution order

of action statements on the basis of conditional expressions

• Conditional expression is evaluated by the program as true or false

• If Then and Select Case statements – Loop structures repeat action statements on the

basis of conditional expressions• While, Do While, For Next, and For Each

• Can nest any of programming control structures

Page 48: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 48

If Then Statement

• Two options for altering the order If (MyBrowser.ToString = "IE") Then Response.Write("You are running Internet Explorer.")Else Response.Write("You are running a different browser.")End If

• Boolean expression uses comparison operators (“true” or “false”) If (MemberDuesPaid.Checked = True) ThenIf (Page.IsPostback = True) ThenIf (DuesPaid.Value < DuesOwed.Value) ThenIf (RadioButtonList1.SelectedIndex > -1) Then

• Can include logical operators in the conditional expressions If ((a = 1) And (b = 2)) ThenIf ((a = 1) Or (b = 2)) ThenIf Not Page.IsPostBack Then

Page 49: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 49

Select Case Statement

• Select Case used to include multiple conditionsSelect Case TxtRole.Value

Case "Manager"

Response.Redirect("Manager.aspx")

Case "Admin"

Response.Redirect("Admin.aspx")

Case Else

Response.Redirect("Member.aspx")

End Select

Page 50: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 50

While Loop

• While loop repeats a block of code while conditional expression is true or Nothing

• Exit While – escape the loop to stop an infinite loop Dim I As Integer = 0

While i < 10

i += 1

Response.Write(i)

End While

Page 51: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 51

Do Loop

• Use Do loops to repeat statements until a conditional is true– Do While will repeat the loop until the condition is False – Do Until will repeat the loop until the condition is True

• Do loop conditional evaluation is done at the end of the loop so there is at least one iteration loop (can fix number of loops)– Variable i (the loop index variable) is initialized to zero– Increment i each time the loop is executed– Exit Do – escape the loop to stop an infinite loop – Unary operator such as ++ used to increment (or decrement with --) a

value by one – VB use 1 += I Dim i As Integer = 0Do While i < 10 i += 1 Response.Write(i)Loop

Page 52: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 52

For Next Loop

• For Next loop repeats statements a fixed number of times

• Identify conditional expression, loop index start number, end number, and step number to increment in the For statement

• Exit For – to exit the loop Dim StartNum, EndNum, StepNum, i As Integer

StartNum = 0

EndNum = 5

StepNum = 2

For i = StartNum To EndNum Step StepNum

Response.Write(i)

Next

Page 53: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 53

For Each Loop

• Each loop accesses elements of a collection, array, or object properties

• Exit For – exit the loop• If SelectedIndex is greater than -1, at least one option was selected• Subtract one because the count always starts at 0

Dim Result As StringIf CBL.SelectedIndex > -1 Then Result = "You selected " Dim i As Integer

For i = 0 To CBL.Items.Count – 1 If CBL.Items(i).Selected Then Result += CBL.Items(i).Text + "<br />" End If NextElse Result = "You did not select a category."End IflblTopics.Text = Result

Page 54: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 54

Nested Statements

• Can nest any (Can combine with If ElseIf) If (Page.IsPostback = True) Then

If (MemberLoginStatus.ToString = "Current") Then

Label1.Text = "Welcome member!"

Else

Label1.Text = "Please login!"

End If

Else

Label1.Text = "Welcome."

End If

Page 55: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 55

Introduction to Web Configuration and Debugging

• Debugging process detects programming errors

• Error handling is a collection of techniques that allow you to identify programming errors in your code, which are often called bugs– Incorrect syntax or spelling errors detected during

development with IntelliSense– Programming logic errors not detected until runtime

• Code interprets error messages and executes when an error is detected, even generating custom error messages and global error handlers

Page 56: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 56

Exception Handling

• Exception object is thrown when a predefined runtime error occurs

• If an exception is raised and not explicitly handled, a general ASP.NET exception occurs, forcing the application to terminate resulting in an error page

• Use when you include database, input/output to the file system, e-mail, or communicating with other applications

• Try-Catch-Finally statement – to handle exceptions

Page 57: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 57

Using Exception Classes to Identify Exception Errors

• The SystemException class is the base class for all predefined exceptions– ExternalException class allows other classes to

indirectly inherit from the SystemException class– ApplicationException class provides a base class to

create user-defined exception objects • SqlException is thrown – SQL Server DataAdapter

when the database server does not exist

• NullReferenceException – a null object is referenced

• IndexOutOfRangeException – an Array object is improperly indexed

Page 58: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 58

Common Error Status Messages

• Status message is returned with HTTP header request– Status Code 200 is Success– Codes exposed by HttpStatusCode property of

System.Net are enumerations and correlate to the HTTP Status Message Codes

– Retrieve using the HttpStatusCode property

Page 59: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 59

Creating a Custom Error Message

• ErrorPage property of the Page directive – default page– customErrors node in the web.config file or Web Site

Administration Tool (WSAT) – Web.config file and customErrors node

(<customErrors>) configure a generic error page with defaultRedirect attribute

– Mode attribute of the customErrors node set to RemoteOnly

• Remote clients are redirected to custom error page• Viewing the web site locally (localhost) displays error

message

Page 60: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 60

Programming Best Practices

• Best practices are commonly accepted activities within a given discipline– Add comments to document the structure and purpose of your

programs to decrease the time required to maintain your program

– Use appropriate data types and programming structures to increase the efficiency of your program

– Avoid narrowing conversions to avoid data conversion errors– Use explicit conversion techniques to avoid data conversion

errors– Use error handling and exception handling techniques when

there are likely to be runtime errors, such as with database connections

Page 61: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 61

Summary

• Variables store data – Assign a data type to a variable when the variable is created – Assign a value when the variable is created

• Properties set the value of a variable defined within an object

• A property is a method that is used to get and set values; you can directly manipulate variables within a class, or you can use a property to indirectly read and change the variable

• ArrayLists and HashTables are examples of collections used to store many data objects

• Server controls can be created or populated programmatically

Page 62: ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition 62

Summary (continued)

• Procedures organize the order in which the code is executed– Event handlers execute code when an event occurs– Functions return values with the keyword Return – Subprocedures do not return a value – Values passed as parameters are separated by commas and

include data type

• Error handling techniques allow you to identify programming errors called bugs – Status message codes are exposed by the HTTPStatusCode

property – SystemException class is the base class for all predefined

exceptions. – Configure custom error pages in web page or web

configuration