ASP.NET Tutorial Michele Leroux Bustamante Get accompanying code samples from the following site: http://www.dotnetdashboard.net/ark/aspnettutorial.aspx IDesign Site: www.idesign.net Newsletter Site: www.dotnetdashboard.net Personal Site: www.mlbtechnologies.com.
Download
Report
Transcript ASP.NET Tutorial Michele Leroux Bustamante Get accompanying code samples from the following site: http://www.dotnetdashboard.net/ark/aspnettutorial.aspx IDesign Site: www.idesign.net Newsletter Site: www.dotnetdashboard.net Personal Site: www.mlbtechnologies.com.
ASP.NET Tutorial
Michele Leroux Bustamante
Get accompanying code samples from the following site:
http://www.dotnetdashboard.net/ark/aspnettutorial.aspx
IDesign Site: www.idesign.net
Newsletter Site: www.dotnetdashboard.net
Personal Site: www.mlbtechnologies.com
Part I: Fundamentals
My First ASP.NET Application
Page Processing & HTML Output
ASP.NET Server Controls
State Management
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
2
Part II: Advanced Techniques
Crash Course in ADO.NET
ASP.NET Database Server Controls
DataBinding
Web User Controls
Custom Web Server Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
3
Part I: Fundamentals
My First ASP.NET Application
Page Processing & HTML Output
ASP.NET Server Controls
State Management
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
4
Creating a New Web Application
From VS.NET, create a new VB.NET
or C# Web Application
By default, files are created beneath
localhost,
in a project
subdirectory
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
5
Creating a New Web Application
Project Files Created in
\Inetpub\wwwroot\MyWebApp
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
6
Testing Your New Application
Compile and run from VS.NET, or…
Compile, then, in your Web browser, type
the URL:
http://localhost/MyWebApp/WebForm1.aspx
Did you get a blank page? Good!
Rename the web form file to default.aspx
Both the .cs/.vb file and .aspx file will be renamed
Do this from Solution Explorer!
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
7
Reviewing the HTML
You can rename the Web form class
WebForm1 -> defaultForm
<%@ Page language=“C#” Codebehind=“default.cs” AutoEventWireup=“false”
Inherits=“MyWebApp.WebForm1” %>
namespace
class
.cs file containing code
for this page
<%@ Page language=“vb” Codebehind=“default.vb” AutoEventWireup=“false”
Inherits=“MyWebApp.WebForm1” %>
namespace
class
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
.vb file containing code
for this page
8
Designing Web Pages
Navigating the Visual Studio IDE
HTML designer
HTML code
Where you will drag and drop Web controls
Edit the generated HTML directly
Codebehind
Separate business logic from user interface
Page and Control events can be handled in
codebehind file
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
9
Web Form Architecture
Combines declarative tags…
HTML, XML, WML, static text
…with code
Clean separation between code & tags
code
<tags>
<tags>
Form1.aspx
Form1.aspx
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
code
Form1.vb/.cs
10
Page Design
Toolbox Controls
HTML Controls
ASP.NET Server Controls
Drag & Drop to Design View
Review HTML in HTML View
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
11
HTML Controls
Drag and drop from toolbox
into the HTML designer
Automatically generates HTML
Select controls in designer,
edit in Properties window
<form id=“form1” method=“post” runat=“server>
<INPUT id=“Button1” type=“button” value="Button"
name="Button1" runat="server“>
<INPUT id=“Text1” type=“text” value="Button"
name="Button1" runat="server“>
</form>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
12
DOCUMENT Properties
Use the Properties window to set
DOCUMENT properties
Converted to HTML automatically
Examples:
bgcolor
Inherits
pageLayout
showGrid
title
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
13
Document Outline Window
HTML Outline
Hierarchical view of HTML code
Select items to find
location in HTML
Delete items easily
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
14
Document Outline Window
Script Outline
Visible in HTML View
List of events for each
"named" HTML control
Use “id” attribute
Can double-click to
create event handlers
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
15
Client Side Script
Project Properties
JavaScript or VBScript
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
16
.ASPX Syntax
A simple page is just static text & HTML
Any HTML page can be renamed .ASPX
Pages may also contain:
Directives: <%@ directive %>
Server controls: <tag runat=server>
Code blocks: <script runat=server>
Data bind expressions: <%# expression %>
Server side comments: <%-- --%>
Render code: <%= %> and <% %>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
17
Page Script
<script language="C#" runat="server">
void Page_Load()
{
// add items to the listbox
lst.Items.Add("http://www.dotnetdashboard.net");
lst.Items.Add("http://www.idesign.net");
}
</script>
<form id="PageScript" method="post" runat="server">
<SELECT id="lst" style="Z-INDEX: 101; LEFT: 37px; WIDTH: 416px;
POSITION: absolute; TOP: 60px; HEIGHT: 164px" size="10"
runat="server" name="lst">
<OPTION>Item1</OPTION>
<OPTION>Item2</OPTION>
</SELECT>
</form>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
18
Page Class
All ASP.NET pages are compiled into
a “stateless” class (object)
Page class provides access to:
Properties to access ASP.NET server objects
Application,
Cache, Request, Response,
Server, Session
Properties describing page state
EnableViewState,
IsPostBack, IsValid
Events that interact with round trip state
Load,
Unload, PreRender, DataBinding
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
19
Page Events
Page Events
Page_Init – Fired when page is initialized
Page_Load – Fired when page is loaded
Control_Event – Fired if a control event is
triggered
Page_Unload – Fired when page is unloaded
from memory
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
20
Page Load Event
Load event is fired on every request
Should ALWAYS use Page.IsPostBack
property to execute conditional logic
public void Page_Load(object s, EventArgs e)
{
if (!Page.IsPostBack) //executes only on initial page load
Message.Text = “initial value”
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
21
Run As Server Control
HTML controls
must be run as
server controls
for events to be
handled in
Codebehind module
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
22
Codebehind - runat=“server”
HTML Controls can be processed on
the server:
<input id=“txtFirstName” type=“text” runat=“server”>
When the Form is submitted to the
page, we can get it’s value like this:
string strFirstName;
strFirstName = txtFirstName.Text;
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
23
Events
ASP.NET Control Events
HTML View
HTML control events can be handled in script
within the HTML page
Codebehind
Can handle events for ASP Server controls
And, HTML controls run on the server
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
24
Client-Side Events
Only HTML
controls listed
here (if they
have an id)
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
25
Client-Side Events
Selected HTML
control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
List of valid
events
26
ASP.NET Controls
Drag and drop from toolbox into the
HTML designer
Automatically generates definition
Placed between form tags in HTML
Select controls in designer, edit
properties in Properties window
<form id=“form1” method=“post” runat=“server>
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:Button id=“Button1" runat="server"></asp:Button>
</form>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
27
Codebehind Module
Write code to respond to page and
control events
Use codebehind control members to
manipulate properties of controls
Code is compiled into the application
assembly
Beneath \bin directory
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
28
HttpRequest Object
Page.Request property
Use it to access:
Form parameters
QueryString parameters
Request headers and content
NOTE: You can save the contents of
the HttpRequest by using the
SaveAs() method!
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
29
HttpResponse Object
Use Page.Response property to access:
Output stream
Output cache
Send data back to the browser
BufferOutput property
Set to true, response is not sent until buffer is flushed
Set to false, Response.Write statements are flushed
to client
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
30
ASP.NET Application Files
VS.NET creates default set of ASP.NET
project files
.csproj or .vbproj
Your project file, stores list of project files settings
.webinfo
Project file indicating the URL for the Web application
based on IIS path (edit if project is moved)
.sln
Solution file, can load more than one project
VS.NET will load the solution
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
31
ASP.NET Application Files
Web.config
Can customize application configuration settings
Can override Machine.config settings
Global.asax
Represents the HttpApplication object
Can write code for application-level events
*.aspx
Default Web forms is WebForm1.aspx
Inherits the Page class
Can add more pages, and rename them as desired
Must select 1 to be the “startup” page
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
32
Global.asax
Inherits HttpApplication
Provides access to the application instance
during an HTTP request
@ Application directive links to codebehind
<%@ Application Codebehind="Global.asax.vb"
Inherits="ViewState.Global" %>
Like .aspx files, .asax can include:
Server side <script> tags
Object creation <object> tags
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
33
Global.asax
Can handle application and
HttpModule events
For example, SessionStateModule
Application.Start
Session.Start
Application.BeginRequest
Application.EndRequest
Session.End
Application.End
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
34
Part I: Fundamentals
My First ASP.NET Application
Page Processing & HTML Output
ASP.NET Server Controls
State Management
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
35
Page Class
Page class is dynamically compiled
by ASP.NET
Requests are handled by instance
HTML is written to the response
stream by the page
*.aspx
Page Object
Codebehind
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
36
*.ASPX Files
Defaults to Codebehind
Can modify @ Page directive
Benefits of Codebehind
Intermediate Language (IL) compiler can catch errors
*.ASPX are JIT compiled, users see uncaught errors
Clean separation of business logic and user interface
presentation with a preserved event-driven model
Event validation controls perform client-side work, no
need for in-page scripting (most of the time)
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
37
Codebehind
Codebehind inherits
System.Web.UI.Page
Can handle Page events of interest
Page.Init
Page.Load
Page_DataBinding
Page.PreRender
Page.Unload
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
38
Page Events
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
39
The Round Trip
HTTP Request
HTTP Response
Render
Page and
Control
HTML
Page Object
Render
Control
HTML
Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
40
The Round Trip
HTTP Request
HTTP Response
Codebehind
Source
.aspx
Create
Page Object
Page Class IL
JIT Compiler
Populate
Members
Page Object
Fire
Events
Render
HTML
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
41
Page Processing
Page/Control events get executed on
the server during page processing
First, the Page.Load event for
requested page
Followed by:
Other page events
Other “cached” control events
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
42
Control Events
Posted form parameters indicate:
Which control initiated HTTP POST
Selected control values
ASP.NET determines which events to
fire
Based on changes in control values
Based on initiator of POST
Some controls can trigger a POST
Button click, Textbox change, Listbox select
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
43
HTTP POST: Button Click
Example:
Enter a new TextBox value
Select from a DropDownList or ListBox
Click a Button
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
44
HTTP POST: Button Click
POST /ASPNETVB/ViewState/WebForm1.aspx HTTP/1.1
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 135
Content-Type: application/x-www-form-urlencoded
Accept: ...; Accept-Encoding: gzip, deflate
Accept-Language: en-us
Cookie: .ASPXAUTH=...;
ASP.NET_SessionId=ns53k155dbrbid21tccazt2e
Host: localhost
Referer: http://localhost/ASPNETVB/ViewState/WebForm1.aspx
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR
1.0.3705)
__VIEWSTATE=dDwxMTIxMTQ1NzU1Ozs%2BAXQdcFai%2F004j3lupIyx0ltGA4U%3D&TextBo
x1=goodbye&Button1=Select&DropDownList1=Item+4&ListBox1=Item+3
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
45
HTTP POST: Button Click
Form parameters indicate user
entries:
TextBox1=goodbye
Button1=Select
DropDownList1=Item 4
ListBox1=Item 3
__VIEWSTATE=dDwxMTIxMTQ1NzU1Ozs%2BAXQdcFai%2F004j3lupIyx0ltGA4U%3D&TextBo
x1=goodbye&Button1=Select&DropDownList1=Item+4&ListBox1=Item+3
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
46
Accessing Form Parameters
Page members are recreated on the
round-trip
If view state is enabled
Control names in codebehind match
.aspx identifiers
// Control Members
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.DropDownList DropDownList1;
// Code to access member values
s = TextBox1.Text;
s = DropDownList1.SelectedItem.Text;
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
47
Accessing Form Parameters
Request.Form property contains
name/value pairs
Regardless of view state
s = Request.Form[“TextBox1”];
s = Request.Form[“DropDownList1”];
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
48
HTML Output
ASP.NET generates HTML output
Automatic management of browser output
Hidden <input>
__VIEWSTATE field stores persisted page and
control data between round trips
<body MS_POSITIONING="FlowLayout">
<form name="Form1" method="post" action="WebForm1.aspx" id="Form1">
<input type="hidden" name="__VIEWSTATE"
value="dDwxNDI1MDc1NTU1Ozs+BikBQY0EO1e4Kf6Hy4QBNSYWNZM=" />
....
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
49
HTML Output
Client Script
Emitted with HTML output as client-side script
block
ASP.NET validation controls emit client script
<body MS_POSITIONING="FlowLayout">
<form name="Form1" method="post" action="WebForm1.aspx"
language="javascript" onsubmit="ValidatorOnSubmit();" id="Form1">
<input type="hidden" name="__VIEWSTATE"
value="dDwxNDI1MDc1NTU1Ozs+BikBQY0EO1e4Kf6Hy4QBNSYWNZM=" />
<script language="javascript"
src="/aspnet_client/system_web/1_0_3705_288/WebUIValidation.js"></script>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
50
Part I: Fundamentals
My First ASP.NET Application
Page Processing & HTML Output
ASP.NET Server Controls
State Management
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
51
HTML vs. Server Controls
HTML Controls
Follow DHTML object model
Fewer Properties, Methods, Events
Valuable when no server interaction, or client
side events are also necessary
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
52
HTML vs. Server Controls
ASP.NET Server Controls
Similar to Windows Forms object model
More functionality:
DataGrid, DataList, Calendar
Different syntax
Requires JIT compilation
First page load is affected
Are always run on the server
Round trips can be managed
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
53
WebControls Namespace
System.Web.UI.WebControls
Contains classes for creating Web server controls
Base Class WebControl
Contains common members for all Web server controls
BackColor, ForeColor, Font, Height, Width etc.
Web server controls render their own HTML
Page class is the container for controls
Controls render their own HTML as Page is rendered
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
54
Web Server Controls
Some Shared Properties:
AutoPostBack – should events be posted or
cached?
EnableViewState – property persistence
CssClass – style sheet class
Tooltip – “title” attribute of HTML element
Visible/Enabled
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
55
Button
Can be a submit button or command
button
Default is submit button
Handle the Click event
Set CommandName, CommandArgument
property
Handle Click or Command event
Both events are fired on submit
Command event receives CommandEventArgs
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
56
ImageButton, Image
ImageButton is similar to Button
Handle Click or Command events
Displays an image
Properties: ImageAlign, ImageUrl,
AlternateText
Image displays an image
No postback events
Properties: ImageAlign, ImageUrl,
AlternateText
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
57
LinkButton, HyperLink
LinkButton creates a hyperlink with
Button functionality
Handle Click or Command events
HyperLink creates a hyperlink
Link directly to another page, no postback
Can display text or image
Properties: Text, ImageUrl, NavigateUrl,
Target
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
58
TextBox
TextMode Property
SingleLine, MultiLine, Password
TextChanged Event
Triggers server post if the AutoPostBack
property is true
Otherwise, event is cached until post occurs
Event will still be triggered, not guaranteed in
what order compared to other control server
events
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
59
List Controls
Similar to Windows Forms controls
Support Data Binding (covered later)
Base Class WebControls.ListControl
DropDownList
ListBox
CheckBoxList
RadioButtonList
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
60
Validation Controls
Validation controls inherit BaseValidator
Which inherits Label
Which inherits WebControl
Validate associated input control
Can apply multiple validation controls to a single
control
Support client-side validation
Deliver JavaScript to the client (no coding necessary!)
Avoid round trip for validation
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
61
Validation Controls
Place control on the form where error
messages should appear
Error message will be displayed if
validation fails
Can be validated on client or server
(defaults to client validation)
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
62
Validation Controls
Text appears if validation fails
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
63
Validation Controls
RequiredFieldValidator
RangeValidator
RegularExpressionValidator
CustomValidator
CompareValidator
ValidationSummary
Can create custom validation controls
Inherit BaseValidator
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
64
Common Properties
ControlToValidate – which input control
to validate
EnableClientScript – controls
client/server validation
ErrorMessage – message to display in
ValidationSummary control or in this
control
Text – overrides display in this control,
use * if using ValidationSummary control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
65
RequiredFieldValidator
Validates the specified control for
user input
Compares input value to IntialValue
property
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
66
RangeValidator
Specify a data type to compare
Specify a maximum and minimum
Validation succeeds if
input data is empty
Use
RequiredFieldValidator
to enforce value
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
67
RegularExpressionValidator
Matches input against a pattern
E-mail, Phone Numbers, SSN
Set ValidationExpression property
Dialog box supports predefined choices
Can create custom expression
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
68
RegularExpressionValidator
Client validation uses JScript
Server uses RegEx
Validation succeeds if input
data is empty
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
69
CompareValidator
Compare the validated control input value
with another control’s input value
ControlToValidate, ControlToCompare properties
Compare to a static value
ValueToCompare, Type properties
Use Operator property to
indicate method of
comparison
Measure equality
Perform data type checks
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
70
CustomValidator
User-defined validation for input
For client validation specify
ClientValidationFunction
For server validation,
handle ServerValidate
event
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
71
ValidationSummary
ErrorMessage property values will be
listed in summary control
Text property displays in control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
72
Server-Side Validation
Server validation always performed
Page.Validate initiates validation
By default, validation happens after
Page.Load event, before individual
control events
Invoked by ASP.NET
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
73
Server-Side Validation
Page.Validate method must be
explicitly called prior to checking
Page.IsValid property during
Page.Load
Can override failed validation by
correcting problem and re-validating
(call Page.Validate)
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
74
Part I: Fundamentals
My First ASP.NET Application
Page Processing & HTML Output
ASP.NET Server Controls
State Management
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
75
State Management
Application State
Data for an entire application
Limited use for frequently used, static data
Session State
Isolates data for a specific user
Default session timeout is 20 minutes, can be
configured
View State
Persistence of page and control properties
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
76
HttpApplicationState
Exposed through intrinsic Application
object
HttpApplication.Application
HttpContext.Application
Page.Application
Stores Key/Value Pairs
Add any type of object to the collection
Access using standard collection syntax, by
name or index value
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
77
Application Values
HttpApplication.StaticObjects
Collection
Stores object with application scope created
using the <object> tag
// setting values
Application.Add(“dbconnect", "Provider=SQLOLEDB.1;…”);
or
Application[“dbconnect”] = "Provider=SQLOLEDB.1;…”;
// getting values
String s = (String)Application[“dbconnect"];
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
78
Application StaticObjects
Generate object with scope via
global.asax
Instantiated when application is
started
Access via
Application.StaticObjects
Use Lock(), UnLock() to protect
state
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
79
Application StaticObjects
// in global.asax
<object id=“appobj" scope="application"
class="StateManagement.UrlInfo" runat="server"/>
// setting value when application is loaded
Application.Lock();
UrlInfo obj = (UrlInfo)Application.StaticObjects[“appobj"];
obj.Url="http://www.idesign.net";
obj.Title="IDesign Associates";
Application.UnLock();
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
80
HttpApplicationState
Limitations
Application state information is cleared when
application is restarted
Not shared across multiple servers (web
farms)
Uses memory resources
Only thread safe objects should be saved
Locking can cause scalability issues
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
81
HttpSessionState
Exposed through intrinsic Session
object
HttpApplication.Session
HttpContext.Session
Page.Session
Stores Key/Value Pairs
Add any type of object to the collection
Access using standard collection syntax, by
name or index value
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
82
Session Values
HttpSessionState.StaticObjects
Collection
Stores object with session scope created
using the <object> tag
// setting values
Application.Session.Add(“name",”Joe Smith”);
or
Application.Session[“name“] = ”Joe Smith”;
// getting values
String s = (String)Application.Session[“name"];
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
83
Session StaticObjects
Generate object with scope via
global.asax
Instantiated when each session is
started
One object for each active session
Access via Session.StaticObjects
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
84
Session StaticObjects
// in global.asax
<object id=“sessionobj" scope="application"
class="StateManagement.UrlInfo" runat="server"/>
// setting value when application is loaded
UrlInfo obj =
(UrlInfo)Application.Session.StaticObjects[“sessionobj"];
obj.Url="http://www.idesign.net";
obj.Title="IDesign Associates";
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
85
Session Configuration
Machine.config
By default enables session state
Can override in Web.config
EnableSessionState
Attribute of the @ Page directive
Set to False for pages that don’t require a
session object
Delays creation of session object
Can’t use Session object from pages that
have this disabled
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
86
ViewState
Used to persist ASP.NET server
control state between round trips
Implemented with a hidden field in
client HTML
Can be disabled per page or control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
87
ViewState
EnableViewState=true
<%@ Page EnableViewState=“True” … %>
<input type="hidden" name="__VIEWSTATE"
value="dDwyMTIzNzU4NjczO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDM+Oz47bDx0PHQ8O3A8bD
xpPDA+O2k8MT47aTwyPjs+O2w8cDxDb2xvciBbQWxpY2VCbHVlXTtDb2xvciBbQWxpY2VCbHV
lXT47cDxDb2xvciBbQXF1YV07Q29sb3IgW0FxdWFdPjtwPENvbG9yIFtBcXVhbWFyaW5lXTtD
b2xvciBbQXF1YW1hcmluZV0+Oz4+Oz47Oz47Pj47Pj47PkZfIFK00pyBR1IaAbVIeLcMIvyz"
/>
EnableViewState=false
<%@ Page EnableViewState=“False” … %>
<input type="hidden" name="__VIEWSTATE"
value="dDwyMTIzNzU4NjczOzs+e1hHXUI/yYEBrzVT8KuMABh8T7A=" />
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
88
ViewState
You can save custom state
information from page to page using
ViewState
// setting values
this.ViewState[“customerid"] = “12345";
// getting values
String s = (String)ViewState[“customerid"];
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
89
Part II: Advanced Techniques
Crash Course in ADO.NET
ASP.NET Database Server Controls
DataBinding
Web User Controls
Custom Web Server Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
90
ADO.NET Data Providers
Set of classes interacting with a
specific type of datasource
Optimized access
Provided with .NET
SQL Server Provider
OLE DB Provider
Other providers can be downloaded
from Microsoft
I.e., .NET Data Provider for Oracle
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
91
Data Provider Objects
ADO.NET Classes supporting
interaction with database providers
Categories of classes:
Connection
Command
DataReader
DataSet
DataAdapter
DataView
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
92
Data Access – Basic Steps
Create and Open Connection
Create Command object with SQL query
statements or Stored Procedure name
Execute command and retrieve data
Manually iterate through dataset results
OR
Bind dataset results directly to Web
controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
93
Connection Object
OleDbConnecton or SqlConnection
Implements IDbConnection
Establish and terminate data source
connection
Properties initialized by constructor
ConnectionString
Database
DataSource
Must be explicitly closed
Call Close() or Dispose()
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
94
Connection Object
SqlConnection objSQLConnection = new SqlConnection("Data Source=.;
Initial Catalog=pubs; UID=sa; PWD=");
objSQLConnection.Open();
// do work
objSQLConnection.Close()
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
95
Connection String Examples
Connection string is database-specific
SQL Server Example:
"Data Source=.; Initial Catalog=pubs; UID=sa; PWD="
"server=localhost; database=pubs; uid=sa”
Microsoft Access (*.mdb) Example:
“PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=[path]authors.mdb”
DSN Example:
“DSN=myDSN”
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
96
Command Object
OleDbCommand or SqlCommand
Implements IDbCommand
Execute SQL statements or Stored
Procedures against datasource
Requires a valid Connection be
opened prior to execution
Connection property
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
97
Command Object
Commands are executed to return data
ExecuteNonQuery()
ExecuteReader()
ExecuteScalar()
ExecuteXmlReader() – SqlCommand only
CommandType indicates how command
should execute against an open
connection
SQL query is default setting
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
98
ExecuteReader()
Returns IDbReader object
SqlCommand returns SqlDataReader
OleDbCommand returns OleDbDataReader
SqlCommand objSQLCommand;
string strSQL = "select * from authors";
objSQLCommand = new SqlCommand(strSQL, objSQLConnection);
SqlDataReader reader = objSQLCommand.ExecuteReader();
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
99
Sample SQL Queries
SELECT list of fields FROM table name
SELECT * FROM Titles
SELECT Title, [Year Published], ISBN FROM Titles
SELECT Titles.Title, Titles.[Year Published], Titles.ISBN,
Publishers.Name FROM Titles
SELECT list of fields FROM table name WHERE condition
SELECT * FROM Titles WHERE [Title] = ‘some title’
SELECT * FROM Titles WHERE [Year Published] > 1990
SELECT list of fields FROM table name WHERE condition ORDER BY field
SELECT * FROM Titles WHERE [Year Published] = 1990 ORDER BY Title
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
100
DataReader Object
OleDbDataReader or SqlDataReader
Implements IDbReader
Read-only and forward-only access
to a set of rows from the datasource
Lightweight, high-performance
access
Reads only 1 record at a time
Cannot be cached on the server
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
101
DataReader Object
Iterating through a DataReader
SqlDataReader reader = objSQLCommand.ExecuteReader();
while (reader.Read()) {
// Example: get values from the first field
string s = (string)reader.GetValue(0);
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
102
DataReader Object
Assigning a DataReader to the
DataGrid.DataSource
SqlDataReader reader = objSQLCommand.ExecuteReader();
dagMain.DataSource = reader;
dagMain.DataBind();
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
103
DataSet Object
In-memory representation of XML or
datasource
Disconnected, remotable
Not tied to a provider
Manipulation of
relational data
Tables, Rows,
Columns, Constraints,
Relationships
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
104
DataSet Object
System.Data.DataSet ds = new System.Data.DataSet();
SqlDataAdapter da = new SqlDataAdapter(objSQLCommand);
int n = da.Fill(ds);
foreach (DataTable tbl in ds.Tables) {
foreach (DataRow tr in tbl.Rows) {
foreach (object o in tr.ItemArray)
// access to fields
}
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
105
DataAdapter Object
OleDbDataAdapter or SqlDataAdapter
Implements IDbDataAdapter
IDbDataAdapter inherits IDataAdapter
Bridge between DataSet and data source
Can update the data source using
specified SQL commands
Can generates a DataSet or DataTable
Use Fill() method from prior examples
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
106
Part II: Advanced Techniques
Crash Course in ADO.NET
ASP.NET Database Server Controls
DataBinding
Web User Controls
Custom Web Server Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
107
Core Databound Controls
ListControl (Base)
DropDownList
ListBox
CheckBoxList
RadioButtonList
DataGrid
DataList
Repeater
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
108
Common Binding Properties
DataSource – source of data binding
DataValueField – field from data source
that provides the value of each item
DataTextField – field from data source to
display
DataMember – indicates a member from
a multi-member DataSource (i.e., multiple
tables in a DataSet)
DataTextFormatString – format string
to be used on data bound to the control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
109
Bound List Controls
Bind to an array
Specify DataSource
Issue DataBind() for the control or
page
string[] colors =
System.Enum.GetNames(typeof(System.Drawing.KnownColor));
this.ListBox1.DataSource=colors;
this.DataBind();
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
110
Bound List Controls
Bind to an XML file
Specify DataSource, DataTextField,
and DataValueField (optional)
Issue DataBind() for control or page
System.Data.DataSet ds = new DataSet("cultures");
string sPath = this.MapPath("");
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}\\cultures.xml", sPath);
ds.ReadXml(sb.ToString());
lstCultures.DataSource=ds;
lstCultures.DataValueField = "value";
lstCultures.DataTextField = "descrip";
lstCultures.DataBind();
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
111
Bound List Controls
Bind to a particular column
Specify DataSource, DataTextField,
and DataValueField (optional)
Issue DataBind() for control or page
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
112
Bound List Controls
SqlConnection objSQLConnection = new
SqlConnection("Data Source=.; Initial Catalog=pubs; UID=sa; PWD=");
SqlCommand objSQLCommand;
string strSQL = "select * from authors";
objSQLConnection.Open();
objSQLCommand = new SqlCommand(strSQL, objSQLConnection);
System.Data.DataSet ds = new System.Data.DataSet();
SqlDataAdapter da = new SqlDataAdapter(objSQLCommand);
int n = da.Fill(ds);
ddl.DataSource=ds;
ddl.DataTextField="au_fname";
ddl.DataValueField="au_fname";
ddl.DataBind();
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
113
DataGrid Control
Bind to a data source
Specify DataSource
Issue DataBind() for the control or page
System.Data.DataSet ds = new DataSet("cultures");
string sPath = this.MapPath("");
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}\\cultures.xml", sPath);
ds.ReadXml(sb.ToString());
this.DataGrid1.DataSource=ds;
this.DataGrid1.DataBind();
AutoGenerateColumns is true by default
Set to false if specifying columns to bind
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
114
DataGrid Appearance
Header and Footer
FooterStyle, ShowFooter
HeaderStyle, ShowHeader
Row Appearance
ItemStyle
SelectedItemStyle
AlternatingItemStyle
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
115
DataGrid Paging
AllowPaging
Enables paging, disabled by default
PageSize defaults to 10
PagerStyle
Set properties of the paging area
Custom paging also supported
Optimize process for large datasets
Greater control over paging process
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
116
DataGrid Paging
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
117
DataGrid Paging
PageIndexChanged Event
Handle this to complete implementation for paging
DataGridPageChangedEventArgs provides access to
selected page index
private void dagMain_PageIndexChanged(object source,
System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
dagMain.CurrentPageIndex = e.NewPageIndex ;
dagMain.DataBind();
}
Bound data is lost on round-trip
Must rebind data source after setting the page index
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
118
DataGrid Columns
Can indicate specific columns and
fields to bind to
Can format, sort,
alter column header
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
119
DataGrid Columns
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
120
DataGrid Commands
Can add button columns for
selection, edit/update/cancel, or
delete
Should handle events for each button
action
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
121
DataGrid Commands
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
122
DataGrid Commands
Events provided for each command:
CancelCommand, DeleteCommand,
EditCommand, UpdateCommand,
SelectIndexCommand
private void OnSelectedIndexChanged(object sender,
System.EventArgs e)
{
// SelectedItem has been set when this event is triggered
TableCellCollection cells = DataGrid1.SelectedItem.Cells;
Response.Write(String.Format(“Selected row contains:{0},{1},{2}<br>“,
cells[0].Text, cells[1].Text, cells[2].Text));
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
123
DataGrid Commands
ItemCommand Event is invoked for
all commands
Invoked prior to individual
commands
Can check command name using
static members
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
124
DataGrid Commands
private void OnItemCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == DataGrid.SelectCommandName)
{
// Cell information is available from the
// DataGridCommandEventArgs
string s = e.Item.Cells[0].Text;
// at this time, selectedIndex is -1,
// so if accessing the SelectedItem
// in this handler, must set SelectedIndex first
DataGrid1.SelectedIndex = e.Item.ItemIndex;
s = DataGrid1.SelectedItem.Cells[0].Text;
// s holds productId
}
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
125
DataList Control
Initialize similar to DataGrid
Set DataSource and issue DataBind() command
Handle command events
Must define templates for rows and
columns
Using VS.NET editor
Using HTML directly
Programmatically
Does not support automatic paging or
sorting
Use DataGrid for these features
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
126
Editing DataList Templates
VS.NET design environment supports
editing
templates for
header, footer,
items and
separators
Right-click on
control and
select from
Edit Template
menu options
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
127
Templates
Draw HTML or ASP.NET controls from
the ToolBox into template regions
Can edit style such as background
color and font
Header and
Footer
Templates
Regular Item
Template
Alternating Item
with different
background color
Separator
Template
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
Edit Item with TextBox in
place of Labels
128
Part II: Advanced Techniques
Crash Course in ADO.NET
ASP.NET Database Server Controls
DataBinding
Web User Controls
Custom Web Server Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
129
Binding Data
Bind elements of each row using
DataBindings dialog
Accessible from the Properties window
Alternative to editing HTML directly
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
130
Binding Data
List of
bindable
properties
Custom binding
expression
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
131
Binding Data
Bind control to data source
OleDbDataReader rdr = cmd.ExecuteReader();
this.DataList1.DataSource = rdr;
this.DataList1.DataBind();
Data bindings added to HTML view
via DataBindings dialog, or manually
<FooterTemplate>
Last Updated: <asp:Label id="labLastUpdated" runat="server"
BackColor="Transparent"><%# DateTime.Now %></asp:Label>
</FooterTemplate>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
132
Binding Data
Example binding to specific fields in
the data source
DataSource property must be set
before DataBind() issued, and field
names must be correct
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
133
Binding Data
<ItemTemplate><TABLE>
<TR><TD><asp:Label id=labProductName runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "productName") %>'>
</asp:Label><BR>
<asp:Label id=labFilename runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "thumbNailImage") %>'>
</asp:Label></TD>
<TD align="right">
<asp:Image id=img runat="server" ImageAlign="Right"
ImageUrl='<%# DataBinder.Eval(Container.DataItem,
"thumbNailImage","images/{0}") %>'>
</asp:Image></TD>
</TR></TABLE>
</ItemTemplate>
<SeparatorTemplate><HR width="100%" color="#6633ff"
SIZE="1"></SeparatorTemplate>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
134
DataList Appearance
Can arrange HTML
output per row
Further customizable
using DataRepeater
control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
135
Data Binding
Process of tying UI elements to a
datastore such as a DataSet
ASP.NET provides server-side data
binding
Removes issues of browser compatibility
Binds and renders data on the server
Outputs browser-independent HTML
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
136
DataSource Binding
Most ASP.NET server controls
support data binding
Properties Window
Set DataBindings for control
Provides a list of properties
that are bindable for the
selected control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
137
DataBind() Method
Page.DataBind()
Can perform data binding at the page level
Binds all controls on the page
Control.DataBind()
Instance method binds only that control
Binding forces the evaluation of databinding expressions
Renders values to HTML output
DataBinding() event is triggered when
binding occurs for the page
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
138
Data Binding Expressions
Placed between <%# … %>
<tagprefix:tagname property="<%# data-binding expression %> runat="server" />
or
literal text <%# data-binding expression %>
Used to bind control properties
<asp:Label runat="server" Width="212px">
<%# ListBox1.SelectedItem.Text %>
</asp:Label>
Used anywhere in the page
<%# m_SomeValue %>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
139
DataBinder.Eval
Evaluates and formats the result of
late-bound data-binding expressions
Uses late-binding and reflection
Carries overhead, but assists with
data type casting
Can be useful for single-line
formatting
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
140
DataBinder.Eval
Convert “Amount” field to string:
<%# DataBinder.Eval(Container.DataItem, “Amount”) %>
Format “thumbNailImage” field with
path:
<asp:Image id=img runat="server" ImageAlign="Right"
ImageUrl='<%# DataBinder.Eval(Container.DataItem,
"thumbNailImage","images/{0}") %>'>
</asp:Image></TD>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
141
Part II: Advanced Techniques
Crash Course in ADO.NET
ASP.NET Database Server Controls
DataBinding
Web User Controls
Custom Web Server Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
142
Web User Controls
Reusable Web form interface
Only within the same project
Designed just like Web forms
Drag & drop Web controls, write event
handlers, etc.
Unlike custom Web server controls (covered
later)
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
143
Creating Web User Controls
Add a Web User Control to the
project
*.ascx file is added to project
Design as you would a Web page
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
144
Using Web User Controls
From Solution Explorer, drag & drop
the .ascx file to an open Web form
Adds @ Register to HTML
Source file, tag prefix & tag name
<%@ Register TagPrefix="uc1" TagName="Login" Src="Login.ascx" %>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
145
Using Web User Controls
Adds control declaration to HTML
Must be contained within <form> tag for
events to work!
<form id="Form1" method="post" runat="server">
<uc1:Login id="ucLogin" runat="server"></uc1:Login>
</form>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
146
Web User Controls Features
Compiled dynamically at runtime
Can’t be added to the Toolbox
Supports properties!
No Properties Window support
Easy to design using HTML Designer
Can combine Web user controls from
multiple languages on a page
Support for fragment caching
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
147
Fragment Caching
Web User Controls can be cached
@ OutputCache Directive
Placed inside *.ascx file
<%@ OutputCache Duration="30" VaryByParam="none" %>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
148
Fragment Caching
PartialCachingAttribute
Placed in codebehind file, as an attribute to
the Web user control class
Attribute constructor supports supplying only
Duration value
[PartialCaching(30)]
public abstract class Login : System.Web.UI.UserControl
{
// control definition
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
149
Part II: Advanced Techniques
Crash Course in ADO.NET
ASP.NET Database Server Controls
DataBinding
Web User Controls
Custom Web Server Controls
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
150
Custom Web Server Controls
Great for code re-use, maintenance
and specialization
Assembly deployment model
Completely reusable binary component
Can leverage .NET versioning
Single copy shared by multiple projects
Can be deployed to the Global Assembly
Cache (GAC)
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
151
Web Control Library
New Web Control Library project
Project generates one Web control
class by default, can define more
classes
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
152
Web Control Base Classes
System.Web.UI.Control
Base class to Page object & all Web server
controls (some through WebControl)
Properties Provided
ID
EnableViewState
Visible
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
153
Web Control Base Classes
System.Web.UI.WebControls.WebControl
Derived from Control
Base class to Web server
controls
Default base class for a
new Web Control Library
Properties Provided
BackColor, BorderStyle,
CssClass, Enabled, Font,
Visible, Width
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
154
HtmlTextWriter
Render method provides access to the
HtmlTextWriter
Provides methods to write HTML tags and
content to the output stream
AddAttribute, RenderBeginTag, RenderEndTag
Write, WriteLine
Static constants
SelfClosingEndTag, SingleQuoteChar,
SpaceChar
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
155
HtmlTextWriter
HtmlTextWriter rendering code:
protected override void Render(HtmlTextWriter output)
{
output.AddAttribute(HtmlTextWriterAttribute.Alt, “Flower Image”,
true);
output.AddAttribute(HtmlTextWriterAttribute.Src, “flower.jpg”
,
true);
output.AddAttribute("myattribute", “custom attribute info”, false);
output.RenderBeginTag(HtmlTextWriterTag.Img);
output.RenderEndTag();
output.WriteLine();
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
156
HtmlTextWriter
Resulting HTML output:
<img alt=“Flower Image" src=“flower.jpg” myattribute=“custom attribute
info” />
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
157
Render Method
Provides access to the
HtmlTextWriter to send output to the
Web form
Provides methods to write HTML tags and
content to the output stream
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
158
Render Method
protected override void Render(HtmlTextWriter output)
{
output.AddAttribute(HtmlTextWriterAttribute.Alt, "Encoding,
\"Required\"", true);
output.AddAttribute(HtmlTextWriterAttribute.Src,
“http://localhost//ASPNETCS//MLBWebControlClient//peaches_sm.jpg”
, true);
output.AddAttribute("myattribute", "No "encoding "
required", false);
output.RenderBeginTag(HtmlTextWriterTag.Img);
output.RenderEndTag();
output.WriteLine();
}
<img alt="Encoding, "Required""
src="http://localhost//ASPNETCS//MLBWebControlClient//peaches_sm.jpg"
myattribute="No "encoding " required" />
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
159
Using Web Server Controls
From the Tools menu, select Customize
Toolbox…
Browser for your Web server control DLL
Select the control, it will be added to the toolbox
Drag & drop the control to the Web form
Adds @ Register to HTML
Source file, tag prefix & tag name
<%@ Register TagPrefix="cc1" Namespace="OrderImage" Assembly="OrderImage"
%>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
160
Using Web Server Controls
Adds control declaration to HTML
<form id="Form1" method="post" runat="server">
<cc1:WebCustomControl1 id="WebCustomControl11"
runat="server"></cc1:WebCustomControl1>
</form>
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
161
Composite Controls
Implement INamingContainer
No methods or properties
Ensures unique namespace for child controls
in Page hierarchy
Override
Control.CreateChildControls()
Add child controls to Controls collection
Creates a composite control
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
162
Composite Controls
Add to the Controls collection of the
WebControl or Control class
Create Web server controls, set their
properties, including style and
position
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
163
Composite Controls
Create HTML literals, also added to
Controls collection
protected override void CreateChildControls()
{
this.Controls.Add(new LiteralControl("<center>"));
Label label1 = new Label();
label1.Text = "Click the button below.";
this.Controls.Add(label1);
this.Controls.Add(new LiteralControl("</center>"));
this.Controls.Add(new LiteralControl("<br>"));
Button btn = new Button();
btn.Text = "Click Me";
btn.Width=new Unit("50%");
btn.Click += new EventHandler(this.OnClick);
this.Controls.Add(btn);
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
164
Composite Controls
Overriding Control.Render()
For composite controls, call base class
Render()
Child controls will render themselves
Add custom rendering code if desired
protected override void Render(HtmlTextWriter output)
{
// do nothing, allow rendering by composite controls
base.Render(output);
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
165
Presentation Details
Library & Control Name
Displayed in Customize Toolbox dialog
Custom Icon
System.Drawing.ToolboxBitmapAttribute
Applied to the control class
Specify filename or resource item
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
166
Presentation Details
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
167
Presentation Details
[ToolboxBitmap("toolbox.ico")]
[DefaultProperty(“Description"),
ToolboxData("<{0}:ImageInfo runat=server></{0}:ImageInfo>")]
public class ImageInfo : System.Web.UI.WebControls.WebControl,
INamingContainer
{
// Control definition
}
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
168
References
.NET Dashboard
http://www.dotnetdashboard.net
A growing list of articles and code
Web Services Tutorial Site
http://www.dotnetdashboard.net/ark/aspnettutorial.aspx
Tutorial session code samples
Additional references
Copyright 2000-2003 Michele Leroux Bustamante. All rights reserved.
169