Title: ASP'NET Introduction, Creating a Site, Debugging
1ASP.NET Introduction, Creating a Site, Debugging
- David Turton
- Conestoga College
- Institute of Technology Advanced Learning
- http//www.conestogac.on.ca/dturton
- Doon 1D17 x3610
2Objectives
- Static vs dynamic web pages
- HTML controls
- HTML Server controls vs. ASP.NET controls
- ASP server-side processing
- Request/Response
- QueryString, ServerVariables, Redirection
- Page events
- Event-driven programming
- Creating a site web pages in VS.NET 2008
- Hello World! yes, there are tricks
- Debugging Code
3Static and Dynamic Web Applications
- HTML is used to create static content
- Dynamic Web pages are created in response to user
input - Shopping carts
- Patient/customer/membership records
- Online orders with inventory checks
- Keyword search into records
- Personalized web sites
- Appointment books
4Server-side Programming
- Create dynamic Web pages
- Populate controls from a database
- Create/modify HTML content on the fly
- Processing occurs on the server
- Hides process code from users nasties
- Sends static HTML to the browser
- Site becomes browser-independent
- Active Server Pages (ASP)
- Microsoft's implementation of dynamic web pages
- ASP.NET
- .NET framework provides control elements
- Speeds web page development
- Example build a lttablegt vs populate a .NET grid
5Processing Web Pages with ASP
- Client requests a page
- ASP engine retrieves
- HTML template
- Code behind the page
- Does global processing
- Adds user controls (server-side includes)
- Executes the code behind the page
- Modifies page contents
- Renders an HTML page as a response to the browser
6ASP.NET Web FormTwo logical parts
- HTML template
- User interface or presentation layer
- Content
- Controls (HTML elements)
- How page is formatted
- Controls
- HTML elements
- HTML Server controls
- ASP.NET controls
- Filename extension .aspx
- Code Behind the Page
- Server program
- Separate file
- Queries modifies controls on page
- ASP.NET compatible language
- Visual Basic .NET, C, Perl, Java, COBOL, etc.
- Filename same as Web Forms
- file extension identifies the language
- .vb - Visual Basic .NET
- .cs C
Not recommended
HelloWorld.aspx ? HelloWorld.aspx.vb
7HTML Server Controlscan be made accessible by
your code
- HTML Server controls
- Add attributes runat "server" and id "someId"
- HTML control
- ltinput type"text"gt
- HTML Server controls
- ltinput type"text" runat"server" id"userName"/gt
- ltinput typeradio runatserver valueYes
id"visa"/gt Visa - Server-side programs can interact with server
controls - Identified by the id property
- Rendered into a plain HTML control
- Sent to the browser
- Controls can be eliminated from the form sent to
the browser - userName.Visible False
8ASP.NET Controls
- Microsofts version of most HTML controls
- Are rendered into HTML code
- So any browser can handle the results
- Are organized as
- Form Controls
- Data Validation Controls
- User Controls
- Data Controls
- Identified by the prefix asp
- Followed by the name of the control
-
ltaspButton id"btnShow" runat"server"
Text"Show message." /gt
9HTML Server Controls vsASP.NET Server Controls
- Different properties
- HTML Server controls values vary by type
- lblProductName.InnerHTML "Product"
- txtFirstName.Value"David"
- ASP server label control value usually .Text
- lblProductName.Text "Product"
- txtFirstName.Text "David"
- Hint let intellisence in VS.NET help you
- Start typing will show you similar control
names - VB type "me." first
- Place period after control name
- Will display properties methods available
- Pick most likely property or method
- Will describe parameters, if any
10PostbackOnce the HTML is rendered, the program
code is dropped,all variables are flushed,
database result tables are lost
- "Maintaining State"
- Retaining information between web requests
- Retain data on form, including data from
invisible controls - Does not retain program variables
- "Postback"
- sending user data to the server.
- __ViewState
- Hidden encrypted field on page ltinput
typehidden /gt - Servers scratch pad
- Browser holds scratch pad, not server
- Example web site with 10 requests a second
- 90 are not serious queries
- Why would you hold info about each request?
- How long do you hold it?
- Would you want to manually code the data
retention routines?
11Postback Data__ViewState Hidden Field
- lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http//www.w3.org/TR/xhtml1/DTD
/xhtml1-transitional.dtd"gt - lthtml xmlns"http//www.w3.org/1999/xhtml"gt
- ltheadgtlttitlegt
- Untitled Page
- lt/titlegtlt/headgt
- ltbodygt
- ltform name"form1" method"post"
action"logonForm.aspx" id"form1"gt - ltdivgt
- ltinput type"hidden" name"__VIEWSTATE"
id"__VIEWSTATE" value"/wEPDwUJNzgzNDMwNTMzZGSR4n
g5EwWlrtoppSaTbbuyqunw" /gt - lt/divgt
- ltdivgt
- ltspan id"lblName" style"width70pxtext-
alignright"gtNamelt/spangt - ltinput name"txtName" type"text"
id"txtName" /gt - ltbr /gt
- ltspan id"lblPassword" style"width70pxt
ext-align right"gtPasswordlt/spangt - ltinput name"txtPassword" type"text"
id"txtPassword" /gt - ltbr /gt
- ltinput type"submit" name"btnLogon"
value"Logon" id"btnLogon" /gt
12Page Class Events
- Page Class
- variety of methods, functions, and properties
- can be accessed within the code behind the page
- When a page is requested by a client
- page events occur
- Page_Init event
- Initializes the page control hierarchy
- Only run once, when the page is first requested
- Page_Load event
- loads server controls into memory
- occurs every time the page is executed
13Page Class Event Cycle
Sub Page_Load(s As Object, e As EventArgs)
lblMessage.Text "Welcome!" End Sub
You work with these
14Event-Driver Programming
- Programs do nothing except in response to an
event - Page is loaded
- User clicks a button
- User changes a text box or drop-down selection
- This fires the appropriate Event Handler
- Control is passed back to server
- Instructions executed sequentially in the event
handler - No event handler
- Event ignored
- Control not passed to server
- Page_Load event doesn't fire
15Events for Controls on Page
- The user clicks the button
- ltaspButton ID"btnLogon" runat"server"
Text"Logon" /gt - The "click" event for the button fires
- And calls the event handler for it
- Private Sub btnLogon_Click(sender as object, e
as EventArgs) - btnLogon.Text "you clicked me!"
- End Sub
16Sample Event Handlers
- event page is loaded
- Private Sub Page_Load(sender as object, e as
EventArgs) - lblMessage.Text "Go ahead ... you know you
want to." - End Sub
- event user clicks button
- Private Sub btnClick_Click(sender as object, e as
EventArgs) - if (lblMessage.Text.Substring(0, 2) "Go")
Then - lblMessage.Text "Hello World!"
- else
- lblMessage.Text "Only once, please.
- EndIf
- End Sub
id of a label on the form
(yes, there's a logic fault in this code)
17Built-in ASP.NET Objects Objects built into the
Web Server
- HTTPRequest
- Information about the browser, fields on the
form, cookies, digital certificates, etc. - Sent with each page request
- HTTPResponse
- To send information to the browser
- To redirect it to another page
- Session
- To hold data for the duration of the connection
- Similar to cookies
18Page.Request Information
- properties
- Request.TotalBytes
- total bytes in the request
- Request.PhysicalPath
- Request.UserHostAddress
- Request.UrlReferrer.Host
- Request.Browser
- Request.Version
- Request.Platform
- methods
- Request.BinaryRead
- retrieve data sent as part of a POST request
- collections
- Request.ClientCertificate
- fields on the client digital certificate
- Request.Cookies
- cookies the client received from this server
- Request.QueryString
- variables in the query string following the page
URL - Request.ServerVariables
- environment variables.
19Request.QueryStringretrieving data from the URL
Query String
- retrieves variables in the URL query string
- Values following "?
- Use procedures to parse the string
- http//www.dave.com/reg.asp?firstNameDavehearra
dheartv - Request.QueryString full string after "?"
in URL - Request.QueryString.Count variables in
query string - Request.QueryString.Get("firstName") value of
field by this name - returns a comma-delimited string if field has
several values (like "hear") - Request.QueryString.GetValues(hear).GetValue(0)
- If field hear has several values, this returns
the 1st one (index 0)
20Request.ServerVariablesenvironment request
header information
- HEADER_headername value stored in the header
headername - HTTP_headername same, but "_" in headername
searched as "-" - HTTPS returns ON if channel secured by SSL, OFF
if not - LOCAL_ADDR IP address of server receiving the
request - LOGON_USER account user is impersonating on web
server - REMOTE_ADDR IP address of remote client
- REMOTE_PORT client TCP response-port
- REQUEST_METHOD method used to send request GET,
POST, PUT - SERVER_NAME name of the server handling the
request - SERVER_PORT port number request was sent to on
the server - SERVER_PORT_SECURE 1 if request handled by secure
server port - URL base portion of the URL
- etc...
Request.ServerVariables.Get(LOGON_USER)
21Page.Request Accessing information about the
request the requester
Private Sub Page_Load(sender as object, e as
EventArgs) Response.Write("ltbgtPhys Path
lt/bgt" Request.PhysicalPath "ltbr/gt")
Response.Write("ltbgtUser Addr lt/bgt"
Request.UserHostAddress "ltbr/gt") If
Request.UrlReferrer IsNot Nothing Then
Response.Write("ltbgtReferrer URL lt/bgt"
Request.UrlReferrer.Host "ltbr/gt") End If
Response.Write("ltbgtBrowser lt/bgt"
Request.Browser.Browser "ltbr/gt")
Response.Write("ltbgtBrowser vers lt/bgt"
Request.Browser.Version "ltbr/gt")
Response.Write("ltbgtUser O/S lt/bgt"
Request.Browser.Platform "ltbr/gt")
Response.Write("ltbgtServer Variable AUTH_USER
lt/bgt" Request.ServerVariables.Get("AUTH_USER")
"ltbr/gt") End Sub
22The ASP.NET Page.Response Property
- Sends information to the browser
- Identifies the server and server properties
- IP address of the server
- Name and version number of the Web server
software - Cookies collection
- Sends cookies to the browser (to store or just
hold for session) - Status code
- Request was successful or encountered an error
23Redirection
Note ../updatePart.aspx is a relative address
that backs up 1 folder http//www.dave.com/updateP
art.aspx is an absolute address
- Going to a page the browser didn't ask for
- In response to a button click
- To an error page
- To a logon page
- Server can't just go to another page
- Asks the browser to redirect its request to
another page - Redirect to another page (addressed relative to
the current page) - Response.Redirect(updatePart.aspx)
- Redirect, passing values in a QueryString
- Response.Redirect(updatePart.aspx?partId789667"
)
querystring being used to pass a field to next
program
24Web Services
- To access Future Shops catalog from your site
- You could post a link
- Also known as sending your user away
- You could scrape their web site
- Extracting data from the HTML they send
- They could provide a Web Service to their catalog
application - Web Services create business-to-business
applications - Exposes some of your programs over the Internet
- Source file has the extension .asmx
- Used like classes
- Public registry (UDDI)
- Registered public Web Services
- URL, what data they expect, what data they
provide - Third party Web Services are at
http//www.xmethods.com
25Creating Web PagesCreating Hello World!
- David Turton
- Conestoga College
- Institute of Technology Advanced Learning
- www.conestogac.on.ca/dturton
- 1D17 X3610
26Terminology
- A project
- A complete web site or application system
- HTML templates, code, images, databases, etc.
- Contained in a folder named after the project
- Special projects Class libraries
- Centralised collection of classes (utilities)
- Referenced by multiple projects
- A solution
- Information about one or more projects
- Location, last forms you had open, etc.
- Disposable stuff
- Default location My Documents\Visual Studio 2008
27New ASP.NET Project (Web Site)Give it its own
home folder use Pascal notationEnsure the
language used will be Cnot on G ... Novell and
Microsoft don't get along
28ResultProject folder initial files created
Delete Default.aspx ... We'll recreate it later,
using a Master Page for layout.
.aspx
.aspx.cs
Project Folder Data Folder Default
ASP.NET web page C code file for above page
Note HTML source view or WYSIWYG design view
29Adding Web Forms to a Project
Can add a folder, Web Form, HTML page, CSS, XML
file/style, user control, master page, etc New
or Existing
30Hello World!
- Drop a label and a button on the page.
- Double-click the form
- In Page_Load routine
- put "Go ahead " message in label.
- Double-click the button
- In button's "Click" routine
- If "Go ahead" is in the label
- Change it to "Hello World!"
- Otherwise
- Change it to "Only once, please"
Yes, there's a trick to it
31Things to notice
- Control placement is clumsy
- Use lttablegt to manage layout
- Table rows push subsequent rows with them
- Use ltdivgt to manage layout
- With "float" and "width" style attributes
- Use HTML like ltbr /gt and ltpgt
- But we'll wean you off that...
32Things to notice
- You can't assign data directly to a control
- lblMessage "Hello World!"
- It's an "object"
- It has methods (procedures, functions)
- .Focus, .DataBind
- It has properties (attributes, characteristics)
- Which also have properties (.Length) and methods
(.SubString) - What do you want to change? Its colour? Its
text? - Specify the object the property to be affected
- lblMessage.Text "Hello World!"
- Or take a property and execute one of its
methods - lblMessage.Text.SubString(0,2)
33Viewing a Web Page
- Right-click on it in Design View
- Select view in browser
34Things to notice
- "only one click" never comes out
- Always get "Hello World!" message
- Use debug to explore this
35Debug setup- declare breakpoints - program
will stop before executing these lines
Click in border to set break-points
(first time debug is run)
36Debug at breakpoint- at each breakpoint, "F11"
to execute line-by-line- lines are highlighted
before they are executed- "F5" to just run to
the next breakpoint
37Debugging the code
- What you'll find
- Page_Load fires on every visit to the code
- Regardless of what event caused the visit
- But
- Want to change the label only on first load
- Try controlling this
- Boolean IsPostBack
- True is a post-back from an existing page
- False is initial load of the page
38Alternate debugging method
- Can throw comments out periodically
- Just "I'm here" stuff
- Or "the index is " gvCategory.SelectedIndex
- Insert following in your code
- System.Diagnostics.Debug.WriteLine("I'm here")
- Displays in VS.NET Output panel
- If running in debug mode