ASP.NET 2.0 Chapter 2 Introduction to Programming.

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Java Script Session1 INTRODUCTION.
Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
The Web Warrior Guide to Web Design Technologies
VBA Modules, Functions, Variables, and Constants
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Web Development Using ASP.NET CA – 240 Kashif Jalal Welcome to week – 1.1 of…
Using Visual Basic 6.0 to Create Web-Based Database Applications
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Basics of ASP.NET. 2 © UW Business School, University of Washington 2004 Outline Installing ASP.NET and Web Matrix Data Types Branching Structure Procedures.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Introduction to ASP.NET, Second Edition2 Chapter Objectives.
Introduction to ASP.NET
ASP.NET 2.0 Chapter 6 Securing the ASP.NET Application.
ASP.NET Programming with C# and SQL Server First Edition
JavaScript, Third Edition
ASP.NET Programming with C# and SQL Server First Edition
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
VB .NET Programming Fundamentals
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
ASP.NET 2.0 Chapter 2 Introduction to Programming.
INTRODUCTION TO WEB DATABASE PROGRAMMING
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
JavaScript, Fourth Edition
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS.
State Management. What is State management Why State management ViewState QueryString Cookies.
© Minder Chen, ASP.NET 2.0: Introduction - 1 ASP.NET 2.0 Minder Chen, Ph.D. Framework Base Class Library ADO.NET: Data & XML.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Chapter 8 Cookies And Security JavaScript, Third Edition.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Tutorial 10 Programming with JavaScript
Done by: Hanadi Muhsen1 Tutorial 1.  Learn the history of JavaScript  Create a script element  Write text to a Web page with JavaScript  Understand.
Using Client-Side Scripts to Enhance Web Applications 1.
Chapter 2: Using Data.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
ASP.NET OPTIMIZATION. Why Optimize? $$$ Whether you build applications for customers or not, enhanced applications save money.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
XP Tutorial 8 Adding Interactivity with ActionScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Programming with Microsoft Visual Basic th Edition
INTRODUCTION CHAPTER #1 Visual Basic.NET. VB.Net General features It is an object oriented language  In the past VB had objects but focus was not placed.
Overview of Previous Lesson(s) Over View  ASP is a technology that enables scripts in web pages to be executed by an Internet server.  ASP.NET is a.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
Introduction to ASP.NET, Second Edition2 Chapter Objectives.
Variables and Arithmetic Operations
WEB PROGRAMMING JavaScript.
PHP.
Tutorial 10: Programming with javascript
JavaScript: Introduction to Scripting
Presentation transcript:

ASP.NET 2.0 Chapter 2 Introduction to Programming

ASP.NET 2.0, Third Edition2 Objectives

ASP.NET 2.0, Third Edition3 Integrate Programming and Web Forms The Web Form is a web page that can contain: –HTML controls ( ) –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 ( Web server controls ( Controls can be written manually or user can use the visual tools to add them to the Web Form

ASP.NET 2.0, Third Edition4 Integrate Programming and Web Forms (continued) Compiled server programs –Inline in the page using delimiters –Embedded Usually at the top of the page with 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

ASP.NET 2.0, Third Edition5 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 –File location is identified by the CodeFile property –Inherits property indicates that the code behind the page inherits the partial class

ASP.NET 2.0, Third Edition6 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 +

ASP.NET 2.0, Third Edition7 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

ASP.NET 2.0, Third Edition8 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

ASP.NET 2.0, Third Edition9 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

ASP.NET 2.0, Third Edition10 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

ASP.NET 2.0, Third Edition11 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"

ASP.NET 2.0, Third Edition12 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 constant Const TAXRATE As Integer = 8

ASP.NET 2.0, Third Edition13 Working with Different Data Types Text and Strings Numeric Date Boolean –True -1 –False 0

ASP.NET 2.0, Third Edition14 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

ASP.NET 2.0, Third Edition15 Strings Modify string using methods of the String object –Replace – replaces one string with another Concatenation joins one or more strings Dim Contact As String = Company .ToString() & " " –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

ASP.NET 2.0, Third Edition16 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 + = / * - )

ASP.NET 2.0, Third Edition17 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 decimals System.String.Format("{0:C}", ) String.Format("{0:P}", ) Format("Percent", ) 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( , "#,###") Format(24.99, "$#,###.##") Format(0.0554, "0.00%")

ASP.NET 2.0, Third Edition18 Working with Date and Time System.DateTime enclosed within a pair of pound signs Dim MyBirthday As DateTime MyBirthday = #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/ :34

ASP.NET 2.0, Third Edition19 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 to 23; you lose the.50 –Overflow exception is thrown –Not allowed by default because data could be lost –Convert 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

ASP.NET 2.0, Third Edition20 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

ASP.NET 2.0, Third Edition21 The ArrayList Create an ArrayList Dim StateAbbrev As New ArrayList StateAbbrev.Add("IL") StateAbbrev.Add("MI") StateAbbrev.Add("IN") Modify ArrayList items StateAbbrev.Insert(0, "OK") StateAbbrev.Remove("OK") Iterate through the list Dim iPos as Integer iPos = StateAbbrev.IndexOf("OK") Dim MyCount As Integer MyCount = StateAbbrev.Count For I = 0 to MyCount -1 MyStates.Text = StateAbbrev(I) & " " Next

ASP.NET 2.0, Third Edition22 The HashTable HashTable creates index of items using an alphanumeric key like an encyclopedia Modify ArrayList items Dim 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 String For each Customer in HT1 CustomerLabel &= Customer.Value & " " Next Customer

ASP.NET 2.0, Third Edition23 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

ASP.NET 2.0, Third Edition24 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 & " " & _ Request.Browser.Type & " " & Request.Browser.Version & " " & _ Request.Browser.Platform

ASP.NET 2.0, Third Edition25 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 index.aspx?CompanyName=Green%20River&Industry=Electronics Value is retrieved and assigned to a Label control Label1.Text = Request.QueryString("CompanyName")

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[R2 Server.UrlEncode(“The String”)[[ Server.UrlDecode(“The%20String”) List of System.Web.HttpRequest variables and properties view Quickstart Class Browser at ASP.NET 2.0, Third Edition26

ASP.NET 2.0, Third Edition27 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

ASP.NET 2.0, Third Edition28 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 " Response.Write(strMessage)

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(" Keep the ViewState information, and insert true as the second parameter Server.Transfer("Page2.aspx", true) ASP.NET 2.0, Third Edition29

ASP.NET 2.0, Third Edition30 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"

ASP.NET 2.0, Third Edition31 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.Text Session("Date of visit") = DateTime.Now.ToShortDateString Session("URL requested") = Request.Url.ToString Session("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 viewed ViewState("Publisher") = "Course Technology" –Retrieve the value Dim MyPublisher As String = CStr(ViewState("Publisher"))

ASP.NET 2.0, Third Edition32 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

ASP.NET 2.0, Third Edition33 Web Applications Architecture

ASP.NET 2.0, Third Edition34 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

ASP.NET 2.0, Third Edition35 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

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/0836

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/0837

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 Edition38

ASP.NET 2.0, Third Edition39 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 page Imports MyClass()

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 Edition40

ASP.NET 2.0, Third Edition41 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

ASP.NET 2.0, Third Edition42 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)

ASP.NET 2.0, Third Edition43 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 name Sub objectName_event(Sender As Object, _ e As EventArgs) Programming statements go here End Sub

ASP.NET 2.0, Third Edition44 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

ASP.NET 2.0, Third Edition45 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 Integer Dim MyDiscount as Integer If CustomerState = "MI" then MyDiscount = 10 Else MyDiscount = 5 End If Return MyDiscount End Function Parameter and data type passed when you call the function Dim MembershipFee As Integer MembershipFee = GetDiscount("MI")

ASP.NET 2.0, Third Edition46 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()

ASP.NET 2.0, Third Edition47 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

ASP.NET 2.0, Third Edition48 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) Then If (Page.IsPostback = True) Then If (DuesPaid.Value < DuesOwed.Value) Then If (RadioButtonList1.SelectedIndex > -1) Then Can include logical operators in the conditional expressions If ((a = 1) And (b = 2)) Then If ((a = 1) Or (b = 2)) Then If Not Page.IsPostBack Then

ASP.NET 2.0, Third Edition49 Select Case Statement Select Case used to include multiple conditions Select Case TxtRole.Value Case "Manager" Response.Redirect("Manager.aspx") Case "Admin" Response.Redirect("Admin.aspx") Case Else Response.Redirect("Member.aspx") End Select

ASP.NET 2.0, Third Edition50 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

ASP.NET 2.0, Third Edition51 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 = 0 Do While i < 10 i += 1 Response.Write(i) Loop

ASP.NET 2.0, Third Edition52 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

ASP.NET 2.0, Third Edition53 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 String If 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 + " " End If Next Else Result = "You did not select a category." End If lblTopics.Text = Result

ASP.NET 2.0, Third Edition54 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

ASP.NET 2.0, Third Edition55 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

ASP.NET 2.0, Third Edition56 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, , or communicating with other applications Try-Catch-Finally statement – to handle exceptions

ASP.NET 2.0, Third Edition57 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

ASP.NET 2.0, Third Edition58 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

ASP.NET 2.0, Third Edition59 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 ( ) 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

ASP.NET 2.0, Third Edition60 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

ASP.NET 2.0, Third Edition61 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

ASP.NET 2.0, Third Edition62 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