Title: ASP.NET 2.0
1ASP.NET 2.0
- Chapter 2
- Introduction to Programming
2Objectives
3Integrate Programming and Web Forms
- The Web Form is a web page that can contain
- HTML controls (ltpgt)
- 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 (ltp runatserver idP1gtlt/pgt
- Web server controls (ltaspcalendar runatserver
idCalendar1 /gt - Controls can be written manually or user can use
the visual tools to add them to the Web Form
4Integrate Programming and Web Forms (continued)
- Compiled server programs
- Inline in the page using lt gt delimiters
- Embedded
- Usually at the top of the page with ltscriptgt tags
- Set the runatserver 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
5Configure 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 - lt_at_ Page Language"VB" gt
- File location is identified by the CodeFile
property - Inherits property indicates that the code behind
the page inherits the partial class - lt_at_ Page Language"VB" CodeFile"Login.aspx.vb"
Inherits"Login" title" Login Page"
AutoEventWireup"false" gt
6Where 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 runatserver property
- Line continuation character is the underscore
- Do not break strings across lines
- Concatenate strings with or
7Using 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
8Declaring 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
9Declaring 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
10Declaring 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
11Declaring 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"
12Declaring 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
13Working with Different Data Types
- Text and Strings
- Numeric
- Date
- Boolean
- True -1
- False 0
14Working 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
15Strings
- Modify string using methods of the String object
- Replace replaces one string with another
- Concatenation joins one or more strings
- Dim ContactEmail As String CompanyEmail.ToString
() "ltbr /gt" - 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
16Working 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 / - )
17Working 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("0C", 1234.45)
- String.Format("0P", 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")
18Working 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 Hmm") 9/9/2007 1734
19Converting 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
20Working 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
21The 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) "ltbr /gt"
- Next
22The 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 "ltbr
/gt" - Next Customer
23Working 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
24Using 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("V
ARIABLE_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
"ltbr /gt" _ - Request.Browser.Type "ltbr /gt"
Request.Browser.Version "ltbr /gt" _
Request.Browser.Platform
25Using 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?CompanyNameGreen20Riv
erIndustryElectronics - Value is retrieved and assigned to a Label
control - Label1.Text Request.QueryString("CompanyName")
26Using 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 usingR2
- Server.UrlEncode(The String)
- Server.UrlDecode(The20String)
- List of System.Web.HttpRequest variables and
properties view Quickstart Class Browser at
www.asp.net/QuickStart/util/classbrowser.aspx
27Accessing 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
28Working with the Response Object
- Response object is mapped to System.Web.HttpRespon
se 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
Electronicsltbr/gt" - Response.Write(strMessage)
29Working 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 parameter - Server.Transfer("Page2.aspx", true)
30Session Objects
- Session object maintains session state across a
single users session - Session variables stored in the servers 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"
31Session 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.ToShortDat
eString - 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("Publis
her"))
32Saving Data Using a Session Object
33Design .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
34Web Applications Architecture
35Organization 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
36Programming 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
37Creating a Class in ASP.NET
- OOP create custom objects based upon the object
definition - Access procedures and properties of object across
multiple web pages - Object is a set of related, compartmentalized
code based upon a class - Create a user-defined class with no visual
component but with global variables, properties,
and procedures - A component is a class with a visual or graphical
user interface - Often used to store access to the data and
business logic
38Creating a Class in ASP.NET (continued)
- Create object definition, called the base class
or class definition - Class is not accessed directly it is the code
that will be used to create the procedures and
properties of the object - Can create many objects based upon the class
definition - Class is a template for the new object
39Creating a Class in ASP.NET (continued)
- Create an instance of the class
- Instantiation is the process of declaring and
initializing an object from 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 - Use the class need to import on the first line
in the code behind the page - Imports MyClass()
40Creating a Class in ASP.NET (continued)
- 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
41Using 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
42Creating 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)
43Creating Event Procedures
- Event procedure is attached to an object with
events - Not executed until triggered by an event
- Event handler intercepts an event
- n 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
44Page 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
45Creating 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 100 - GetDiscount("MI")
46Creating 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
()
47How Web Applications Interact with the
Systems.Drawing.Graphics.Class
48Using the Systems.Drawing.Graphics.Class
49Dynamically Creating Server Controls
50Dynamically Creating a Hyperlink Control
51Programming 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
52If 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 lt DuesOwed.Value) Then
- If (RadioButtonList1.SelectedIndex gt -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
53Select 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
54While 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 lt 10
- i 1
- Response.Write(i)
- End While
55Do 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 lt 10
- i 1
- Response.Write(i)
- Loop
56For 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
- Loop
57For 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 gt -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 "ltbr /gt"
- End If
- Next
- Else
- Result "You did not select a category."
- End If
- lblTopics.Text Result
58Nested 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
59Introduction 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
60Exception 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
61Using 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
62Common 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
63Creating 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
(ltcustomErrorsgt) 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
64Creating a Custom Error Message (continued)
65Using the Web Site Administration Tool
66Using the Web Site Administration Tool (continued)
- Web configuration file
- ltcustomErrors defaultRedirect"/ch2_genericerror.
aspx" mode"On"gt - lterror statusCode"403" redirect"/ch2_noacces
s.aspx" /gt - lterror statusCode"404" redirect"/ch2_filen
otfound.aspx" /gt - lt/customErrorsgt
67Configuring the Web Application to Use the
Debugger Tool
- Set at page level or in web configuration
- lt?xml version"1.0" encoding"UTF-8" ?gt
- ltconfigurationgt
- ltsystem.webgt
- ltcompilation
- debug"true" defaultLanguage"vb"
- explicit"true" strict"true" gt
- lt/compilationgt
- lt/system.webgt
- lt/configurationgt
68Programming 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
69Summary
- 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
70Summary (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