Server Side Applications - PowerPoint PPT Presentation

1 / 138
About This Presentation
Title:

Server Side Applications

Description:

Consists of static HTML interspersed with script ... Snippets and code sharing. Community. Support. WYSIWYG Controls. Introduction to ASP.NET ... – PowerPoint PPT presentation

Number of Views:249
Avg rating:3.0/5.0
Slides: 139
Provided by: Suka8
Category:

less

Transcript and Presenter's Notes

Title: Server Side Applications


1
Server Side Applications
9
  • Introduction to ASP.NET and Web Forms

2
Agenda
  • Background
  • ASP.NET Overview
  • Programming Model
  • Programming Basics
  • Server Controls
  • Data Binding
  • Conclusion

3
Introduction to ASP.NET and Web Forms
9
  • 1. Background

4
What is ASP?
  • Server-side programming technology
  • Consists of static HTML interspersed with script
  • ASP intrinsic objects (Request, Response, Server,
    Application, Session) provide services
  • Commonly uses ADO to interact with databases
  • Application and session variables
  • Application and session begin/end events
  • ASP manages threads, database connections, ...

5
What is ASP?
ASP page (static HTML, server-side logic)
6
HelloWorld.asp
lthtmlgt ltheadgtlttitlegtHelloWorld.asplt/titlegtlt/headgt
ltbodygt ltform method"post"gt ltinput type"submit"
idbutton1 namebutton1 value"Push Me" /gt lt if
(Request.Form("button1") ltgt "") then
Response.Write "ltpgtHello, the time is "
Now() end if gt lt/formgt lt/bodygt lt/htmlgt
7
ASP Successes
  • Simple procedural programming model
  • Access to COM components set of specification
    and services that facilitates a developer to
    create reusable objects and components for
    running various applications Can be as EXE or
    DLL
  • ActiveX Data Objects (ADO)
  • File System Object Get details about files and
    folders
  • Custom components
  • Script-based no compiling, just edit, save run
  • VBScript, JScript leverages existing skills
  • Support for multiple scripting languages

8
ASP Challenges
  • Coding overhead (too much code)
  • Everything requires writing code!
  • Code readability (too complex code and UI
    intermingled)
  • Maintaining page state After submit button is
    clicked, if we click the back button, we expect
    to maintain scroll position, maintain which
    control had focus, and restore focus, or allow
    server code to focus a new control requires
    more code
  • Reuse is difficult
  • Supporting many types of browsers is difficult
  • Deployment issues (e.g. DLL locking)
  • Session state scalability and availability
  • Limited support for caching, tracing, debugging,
    etc.
  • Performance and safety limitations of script

9
DLL Locking
  • When a COM reference is made to a COM DLL (like
    calling it from ASP), a file lock is placed on
    the COM DLL until the process is finished.  In
    the case of ASP, the web server's process (either
    inetinfo.exe or sometimes dllhost.exe)
    establishes the lock.  This process normally
    doesn't end for a long time.  You either have to
    cycle IIS (cmd iisreset) or reboot.  Then the
    DLL is unlocked.
  • .NET assemblies on the other hand do not have
    this problem because it is not referenced by
    COM.  Even when running in ASP.NET.  The reason
    for this is the way .NET works.  The .NET
    assembly contains intermediate code (MSIL
    MicroSoft Intermediate Language).  MSIL is
    'generic' .NET code.  When an assembly is needed,
    .NET pulls in the .DLL file, and compiles the
    MSIL code to machine code and caches the
    result.  It then turns on a file watch on that
    DLL file and releases the file.  If it sees the
    file change (you recompile or in another way
    update the DLL) it drops the cached machine code
    and recompiles it from the updated DLL.

10
Introduction to ASP.NET and Web Forms
9
  • 2. ASP.NET Overview

11
ASP.NET Overview
  • ASP.NET provides services to allow the creation,
    deployment, and execution of Web Applications
    and Web Services
  • Like ASP, ASP.NET is a server-side technology
  • Web Applications are built using Web Forms
  • Web Forms are designed to make building
    web-based applications as easy as building
    Visual Basic applications

12
Goals
  • Keep the good parts of ASP and improve the rest
  • Simplify less code, easier to create and
    maintain
  • Multiple, compiled languages
  • Fast
  • Scalable
  • Manageable
  • Available
  • Customizable and extensible
  • Secure
  • Tool support

13
Key Features
  • Web Forms
  • Web Services
  • Built on .NET Framework
  • Simple programming model
  • Maintains page state
  • Multibrowser support
  • XCOPY deployment facilitates to install desktop
    applications on client machines using a remote
    web server
  • XML configuration
  • Complete object model
  • Session management
  • Caching
  • Debugging
  • Extensibility
  • Separation of code and UI
  • Security
  • ASPX, ASP side by side
  • Simplified form validation
  • Cookieless sessions

14
HelloWorld.aspx
lt_at_ Page language"c" gt lthtmlgt ltheadgtlt/headgt ltsc
ript runat"server"gt public void B_Click (object
sender, System.EventArgs e) Label1.Text
"Hello, the time is " DateTime.Now lt/scriptgt
ltbodygt ltform method"post" runat"server"gt
ltaspButton onclick"B_Click" Text"Push Me"
runat"server" /gt ltpgt ltaspLabel idLabel1
runat"server" /gt lt/formgt lt/bodygt lt/htmlgt
15
Architecture
  • ASP.NET is built upon
  • .NET Framework
  • Internet Information Server (IIS)

16
Architecture
  • Internet Information Server (IIS)
  • IIS MMC Snap-In (Internet Services Manager)
  • Tool to manage IIS
  • Virtual Directories
  • Provides a mapping between URL and file path

17
Architecture
VB
C
C
JScript

Visual Studio.NET
Common Language Specification
ASP.NET Web Services and Web Forms
Windows Forms
ADO.NET Data and XML
Base Class Library
Web Matrix
Common Language Runtime
Windows
COM Services
18
ASP .NET Web Matrix Project
  • Lightweight, simple, community-oriented tool for
    building ASP.NET apps
  • Full WYSIWYG support
  • Small ( 1.4 Mb)
  • Community features
  • IM integration, code sharing, chat features
  • Available free-of-charge at www.asp.net

19
WYSIWYG Controls
Snippets and code sharing
Community Support
20
Introduction to ASP.NET and Web Forms
9
  • 3. Programming Model

21
Controls and Events
  • Server-side programming model
  • Based on controls and events
  • Just like Visual Basic
  • Not data in, HTML out
  • Higher level of abstraction than ASP
  • Requires less code
  • More modular, readable, and maintainable

22
Controls and Events
Button code ...
List code ...
Text code ...
ASP.NET
Event handlers
Browser
23
ASP.NET Object Model
  • User code executes on the web server in page or
    control event handlers
  • Controls are objects, available in server-side
    code
  • Derived from System.Web.UI.Control
  • The web page is an object too
  • Derived from System.Web.UI.Page which is a
    descendant of System.Web.UI.Control
  • A page can have methods, properties, etc.

24
Postbacks
  • A postback occurs when a page generates an HTML
    form whose values are posted back to the same
    page
  • A common technique for handling form data
  • In ASP and other server-side technologies the
    state of the page is lost upon postback...
  • Unless you explicitly write code to maintain
    state
  • This is tedious, bulky and error-prone

25
Postbacks Maintain State
  • By default, ASP.NET maintains the state of all
    server-side controls during a postback
  • Can use method"post" or method"get"
  • Server-side control objects are automatically
    populated during postback
  • No state stored on server
  • Works with all browsers

26
Server-side Controls
  • Multiple sources of controls
  • Built-in
  • 3rd party
  • User-defined
  • Controls range in complexity and power button,
    text, drop down, calendar, data grid, ad rotator,
    validation
  • Can be populated via data binding

27
Automatic Browser Compatibility
  • Controls can provide automatic browser
    compatibility
  • Can target UpLevel or DownLevel browsers
  • UpLevel browsers support additional
    functionality, such as JavaScript and DHTML
  • DownLevel browsers support HTML 3.2

28
Automatic Browser Compatibility
Button code ...
Button Control
Menu code ...
Menu Control
Text code ...
Text Control
Event handlers
ASP.NET
...
29
Code-behind pages
  • Two styles of creating ASP.NET pages
  • Controls and code in .aspx file
  • Controls in .aspx file, code in code-behind page
  • Supported in Visual Studio.NET
  • Code-behind pages allow you to separate the user
    interface design from the code
  • Allows programmers and designers to work
    independently

lt_at_ Codebehind"WebForm1.cs"
Inherits"WebApplication1.WebForm1" gt
30
Automatic Compilation
  • Just edit the code and hit the page
  • ASP.NET will automatically compile the code into
    an assembly
  • Compiled code is cached in the CLR Assembly Cache
  • Subsequent page hits use compiled assembly
  • If the text of the page changes then the code is
    recompiled
  • Works just like ASP edit, save and run

31
Automatic Compilation
32
Introduction to ASP.NET and Web Forms
9
  • 4. Programming Basics

33
Page Syntax
  • The most basic page is just static text
  • Any HTML page can be renamed .aspx
  • Pages may contain
  • Directives lt_at_ Page Language"C" gt
  • Server controls ltaspButton runat"server" gt
  • Code blocks ltscript runat"server"gtlt/scriptgt
  • Data bind expressions lt gt
  • Server side comments lt-- --gt
  • Render code lt gt and lt gt
  • Use is discouraged use ltscript runat"server"gt
    with code in event handlers instead

34
The Page Directive
  • Lets you specify page-specific attributes, e.g.
  • AspCompat Compatibility with ASP
  • Buffer Controls page output buffering
  • CodePage Code page for this .aspx page
  • ContentType MIME type of the response
  • ErrorPage URL if unhandled error occurs
  • Inherits Base class of Page object
  • Language Programming language
  • Trace Enables tracing for this page
  • Transaction COM transaction setting
  • Only one page directive per .aspx file

35
Server Control Syntax
  • Controls are declared as HTML tags with
    runat"server" attribute
  • Tag identifies which type of control to create
  • Control is implemented as an ASP.NET class
  • The id attribute provides programmatic identifier
  • It names the instance available during postback

ltinput typetext id"text2" runat"server"
/gt ltaspcalendar id"myCal" runat"server" /gt
36
Server Control Properties
  • Tag attributes map to control properties

ltaspbutton id "c1" Text"Foo" runat "server"
gt ltaspListBox id"c2" Rows"5" runat"server" gt
  • Tags and attributes are case-insensitive
  • Control properties can be set programmatically

c1.Text "Foo" c2.Rows 5
37
Maintaining State
  • By default, controls maintain their state across
    multiple postback requests
  • Implemented using a hidden HTML field
    __VIEWSTATE
  • Works for controls with input data (e.g. TextBox,
    CheckBox), non-input controls (e.g. Label,
    DataGrid), and hybrids (e.g. DropDownList,
    ListBox)
  • Can be disabled per control or entire page
  • Set EnableViewState"false"
  • Lets you minimize size of __VIEWSTATE

38
Server Code Blocks
  • Server code lives in a script block marked
    runat"server"
  • Script blocks can contain
  • Variables, methods, event handlers, properties
  • They become members of a custom Page object

ltscript language"C" runat"server"gt ltscript
language"VB" runat"server"gt ltscript
language"JScript" runat"server"gt
39
Page Events
  • Pages are structured using events
  • Enables clean code organization
  • Avoids the Monster IF statement
  • Less complex than ASP pages
  • Code can respond to page events
  • e.g. Page_Load, Page_Unload
  • Code can respond to control events
  • Button1_Click
  • Textbox1_Changed

40
Page Event Lifecycle
Initialize
Page_Init
Restore Control State
Load Page
Page_Load
Control Events
Textbox1_Changed
1. Change Events
Button1_Click
2. Action Events
Save Control State
Render
Page_Unload
Unload Page
41
Page Loading
  • Page_Load fires at beginning of request after
    controls are initialized
  • Input control values already populated

protected void Page_Load(Object s, EventArgs e)
message.Text textbox1.Text
42
Page Loading
  • Page_Load fires on every request
  • Use Page.IsPostBack to execute conditional logic

protected void Page_Load(Object s, EventArgs e)
if (! Page.IsPostBack) // Executes only
on initial page load Message.Text "initial
value" // Rest of procedure executes on
every request
43
Server Control Events
  • Change Events
  • By default, these execute only on next action
    event
  • E.g. OnTextChanged, OnCheckedChanged
  • Change events fire in random order
  • Action Events
  • Cause an immediate postback to server
  • E.g. OnClick
  • Works with any browser
  • No client script required, no applets, no ActiveX
    Controls!

44
Wiring Up Control Events
  • Control event handlers are identified on the tag
  • Event handler code

ltaspbutton onclick"btn1_click"
runat"server"gt ltasptextbox onchanged"text1_chan
ged" runat"server"gt
protected void btn1_Click(Object s, EventArgs e)
Message.Text "Button1 clicked"
45
Event Arguments
  • Events pass two arguments
  • The sender, declared as type object
  • Usually the object representing the control that
    generated the event
  • Allows you to use the same event handler for
    multiple controls
  • Arguments, declared as type EventArgs
  • Provides additional data specific to the event
  • EventArgs itself contains no data a class
    derived from EventArgs will be passed

46
Page Unloading
  • Page_Unload fires after the page is rendered
  • Dont try to add to output
  • Useful for logging and clean up

protected void Page_Unload(Object s, EventArgs e)
MyApp.LogPageComplete()
47
Import Directive
  • Adds code namespace reference to page
  • Avoids having to fully qualify .NET types and
    class names
  • Equivalent to the C using directive

lt_at_ Import Namespace"System.Data" gt lt_at_ Import
Namespace"System.Net" gt lt_at_ Import
Namespace"System.IO" gt
48
Page Class
  • The Page object is always available when handling
    server-side events
  • Provides a large set of useful properties and
    methods, including
  • Application, Cache, Controls, EnableViewState,
    EnableViewStateMac, ErrorPage, IsPostBack,
    IsValid, Request, Response, Server, Session,
    Trace, User, Validators
  • DataBind(), LoadControl(), MapPath(), Validate()

49
Introduction to ASP.NET and Web Forms
9
  • 5. Server Controls

50
Server Controls
  • ASP.NET ships with 50 built-in controls
  • Organized into logical families
  • HTML controls
  • Controls / properties map 11 with HTML
  • Web controls
  • Richer functionality
  • More consistent object model

51
HTML Controls
  • Work well with existing HTML designers
  • Properties map 11 with HTML
  • table.bgcolor "red"
  • Can specify client-side event handlers
  • Good when quickly converting existing pages
  • Derived from System.Web.UI.HtmlControls.HtmlContro
    l
  • Supported controls have custom class, others
    derive from HtmlGenericControl

52
HTML Controls
  • Supported controls
  • ltagt
  • ltimggt
  • ltformgt
  • lttablegt
  • lttrgt
  • lttdgt
  • ltthgt
  • ltselectgt
  • lttextareagt
  • ltbuttongt
  • ltinput typetextgt
  • ltinput typefilegt
  • ltinput typesubmitgt
  • ltinput typebuttongt
  • ltinput typeresetgt
  • ltinput typehiddengt

53
HTML Controls
  • Demo 1 HTMLControls1.aspx
  • Basic page lifecycle with HTML Controls
  • Demo 2 HTMLControls2.aspx
  • More HTML Controls

54
HTML Controls
  • Can use controls two ways
  • Handle everything in action events (e.g. button
    click)
  • Event code will read the values of other controls
    (e.g. text, check boxes, radio buttons, select
    lists)
  • Handle change events as well as action events

55
Web Controls
  • Consistent object model

Label1.BackColor Color.Red Table.BackColor
Color.Blue
  • Richer functionality
  • E.g. AutoPostBack, additional methods
  • Automatic uplevel/downlevel support
  • E.g. validation controls
  • Strongly-typed no generic control
  • Enables better compiler type checking

56
Web Controls
  • Web controls appear in HTML markup as namespaced
    tags
  • Web controls have an asp prefix

ltaspbutton onclick"button1_click"
runat"server"gt ltasptextbox onchanged"text1_chan
ged" runat"server"gt
  • Defined in the System.Web.UI.WebControls
    namespace
  • This namespace is automatically mapped to the
    asp prefix

57
Web Controls
  • Web Controls provide extensive properties to
    control display and format, e.g.
  • Font
  • BackColor, ForeColor
  • BorderColor, BorderStyle, BorderWidth
  • Style, CssClass
  • Height, Width
  • Visible, Enabled

58
Web Controls
  • Four types of Web Controls
  • Intrinsic controls
  • List controls
  • Rich controls
  • Validation controls

59
Intrinsic Controls
  • Correspond to HTML controls
  • Supported controls
  • ltaspbuttongt
  • ltaspimagebuttongt
  • ltasplinkbuttongt
  • ltasphyperlinkgt
  • ltasptextboxgt
  • ltaspcheckboxgt
  • ltaspradiobuttongt
  • ltaspimagegt
  • ltasplabelgt
  • ltasppanelgt
  • ltasptablegt

60
Intrinsic Controls
  • TextBox, ListControl, CheckBox and their
    subclasses dont automatically do a postback when
    their controls are changed
  • Specify AutoPostBacktrue to make change events
    cause a postback

61
List Controls
  • Controls that handle repetition
  • Supported controls
  • ltaspdropdownlistgt
  • ltasplistboxgt
  • ltaspradiobuttonlistgt
  • ltaspcheckboxlistgt
  • ltasprepeatergt
  • ltaspdatalistgt
  • ltaspdatagridgt

62
List Controls
  • Repeater, DataList and DataGrid controls
  • Powerful, customizable list controls
  • Expose templates for customization
  • Can contain other controls
  • Provide event bubbling through their
    OnItemCommand event
  • More about these controls and templates later

63
CheckBoxList RadioButtonList
  • Provides a collection of check box or radio
    button controls
  • Can be populated via data binding

ltaspCheckBoxList id"Check1" runat"server"gt
ltaspListItemgtItem 1lt/aspListItemgt
ltaspListItemgtItem 2lt/aspListItemgt
ltaspListItemgtItem 3lt/aspListItemgt
ltaspListItemgtItem 4lt/aspListItemgt
ltaspListItemgtItem 5lt/aspListItemgt lt/aspCheckBox
Listgt
64
Intrinsic Simple List Controls
  • Demo 1 WebControls1.aspx
  • Assorted intrinsic and list controls
  • Demo 2 WebControls2.aspx
  • Same controls with AutoPostBack

65
Rich Controls
  • Custom controls with rich functionality
  • Supported Controls
  • ltaspcalendargt
  • ltaspadrotatorgt
  • More will be added
  • 3rd party controls are coming
  • Demo RichControls1.aspx

66
Validation Controls
  • Rich, declarative validation
  • Validation declared separately from input control
  • Extensible validation framework
  • Supports validation on client and server
  • Automatically detects uplevel clients
  • Avoids roundtrips for uplevel clients
  • Server-side validation is always done
  • Prevents users from spoofing Web Forms

67
Validation Controls
  • ltaspRequiredFieldValidatorgt
  • Ensures that a value is entered
  • ltaspRangeValidatorgt
  • Checks if value is within minimum and maximum
    values
  • ltaspCompareValidatorgt
  • Compares value against constant, another control
    or data type
  • ltaspRegularExpressionValidatorgt
  • Tests if value matches a predefined pattern
  • ltaspCustomValidatorgt
  • Lets you create custom client- or server-side
    validation function
  • ltaspValidationSummarygt
  • Displays list of validation errors in one place

68
Validation Controls
  • Validation controls are derived from
    System.Web.UI.WebControls.BaseValidator, which is
    derived from the Label control
  • Validation controls contain text which is
    displayed only if validation fails
  • Text property is displayed at control location
  • ErrorMessage is displayed in summary

69
Validation Controls
  • Validation controls are associated with their
    target control using the ControlToValidate
    property
  • Can create multiple validation controls with the
    same target control

ltaspTextBox id"TextBox1" runat"server"
/gt ltaspRequiredFieldValidator id"Req1"
ControlToValidate"TextBox1"
Text"Required Field" runat"server" /gt
70
Validation Controls
  • Page.IsValid indicates if all validation controls
    on the page succeed

void Submit_click(object s, EventArgs e) if
(Page.IsValid) Message.Text "Page is
valid!"
71
Validation Controls
  • Display property controls how the error message
    is shown
  • Static fixed layout, display wont change if
    invalid Space for the validation message is
    allocated in the page layout
  • Dynamic Space for the validation message is
    dynamically added to the page if validation fails
  • None Validation message is never displayed can
    still use ValidationSummary and Page.IsValid
  • Type property specifies expected data type
    Currency, Date, Double, Integer, String

72
Validation Controls
  • Can force down-level option
  • Only server-side validation

lt _at_ Page Language"c"
ClientTarget"DownLevel" gt
73
Validation Controls
  • Demo ValidationControls1.aspx
  • Demonstrates each type of validation control

74
Introduction to ASP.NET and Web Forms
9
  • 6. Data Binding

75
How to Populate Server Controls?
  • Specify the data in the controls tags
  • Not dynamic cant get data from a database
  • Write code that uses the controls object model
  • This is okay if you need to populate a simple
    value or list, but quickly gets too complicated
    for populating sophisticated displays
  • Data binding
  • Create an object that holds the data (DataSet,
    Array, string, int, etc.)
  • Associate that object with the control

76
What Is It?
  • Provides a single simple yet powerful way to
    populate Web Form controls with data
  • Enables clean separation of code from UI
  • Supports binding to any data source
  • Properties, expressions, method calls
  • Collections (Array, Hashtable, etc.)
  • DataSet, DataTable, DataView, DataReader
  • XML
  • One way snapshot model
  • Requires code to reapply to data model

77
What Is It?
  • Allows you to specify an expression
  • When the DataBind method of the control is
    called, the expression is evaluated and bound
  • DataBind for a single control (and subcontrols)
  • Page.DataBind binds all controls on a page
  • Works for scalars, e.g. Label control
  • Works for lists, e.g. DropDown control, ListBox
    control, etc.
  • Enables the use of templates

78
Scalar Expressions
  • Data binding expression lt expression gt
  • Expression is evaluated when DataBind() is called

ltaspLabel idlabel1 Textlt "The result is "
(1 2) ", the time is " DateTime.Now.ToLong
TimeString() gt runat"server" /gt public void
Page_Load(object s, EventArgs e) if (!
Page.IsPostBack) Page.DataBind()
79
Scalar Expressions
  • Demo DataBinding1.aspx
  • Data binding to simple, scalar expressions

80
Simple Lists
  • Data binding a list creates a user interface
    element for each item in the list
  • Each item contains text (displayed to user) and
    an optional value (not displayed)
  • The simple list controls
  • ltaspListBoxgt
  • Single or multiple select
  • ltaspDropDownListgt
  • ltaspRadioButtonListgt
  • ltaspCheckBoxListgt

81
Simple Lists
  • Steps to data bind a list control
  • Declare the list control
  • Optionally set DataValueField and DataTextField
  • Set its DataSource
  • Call DataBind() method

82
Simple Lists
  • Demo DataBinding2.aspx
  • Data binding to simple lists

83
Database
  • Data binding can be used to populate server
    controls with data from a database
  • Each UI element corresponds to a row
  • Bind to a DataReader (preferred)
  • Bind to a DataView of a DataSet
  • Specify value and text with DataValueField and
    DataTextField, respectively
  • Each of these corresponds to a column

84
Data Source Example
DataView GetSampleData() DataSet ds
SqlConnection cxn SqlDataAdapter adp cxn
new SqlConnection("serverlocalhost "
"uidsapwddatabaseNorthwind") adp new
SqlDataAdapter( "select CategoryID,
CategoryName from Categories", cxn) ds
new DataSet() adp.Fill(ds, "Categories")
return ds.Tables"Categories".DefaultView
85
List Binding Examples
void Page_Load(object s, EventArgs e)
ListBox1.DataSource GetSampleData()
ListBox1.DataValueField "CategoryID"
ListBox1.DataTextField "CategoryName"
ListBox1.DataBind() ltaspListBox id"ListBox1"
runat"server" /gt
void Page_Load(object s, EventArgs e)
ListBox1.DataBind() ltaspListBox id"ListBox1"
runat"server" DataSourcelt GetSampleData()
gt DataValueField"CategoryID"
DataTextField"CategoryName" /gt
86
Binding to a Database
  • Demo DataBinding3.aspx
  • Data binding to a database

87
DataGrid
  • Full-featured list output
  • Default look is a grid
  • Default is to show all columns, though you can
    specify a subset of columns to display
  • Columns can be formatted with templates
  • Optional paging
  • Updateable

88
Binding to All Columns
  • Binding all columns in the datasource
  • Declare an ltaspDataGridgt
  • Set its DataSource
  • Call DataBind()

void Page_Load(object s, EventArgs e)
myDataGrid.DataSource GetSampleData()
myDataGrid.DataBind() ltaspdatagrid
id"myDataGrid" runat"server" /gt
89
Binding to Specific Columns
  • By default, DataGrid will display all columns
  • To control columns to display
  • Set AutoGenerateColumns"false"
  • Specify Columns property
  • Add column definition
  • BoundColumn
  • TemplateColumn
  • ButtonColumn, EditCommandColumn, HyperlinkColumn

90
Binding to Specific Columns
  • Binding to specific columns in the datasource
  • Declare an ltaspDataGridgt
  • Declare its Columns collection
  • Set its DataSource
  • Call its DataBind() method

ltaspdatagrid id"myDataGrid"
autogeneratecolumns"false" runat"server"gt
ltColumnsgt ltaspBoundColumn HeaderText"Id"
DataField"title_id" /gt ltaspBoundColumn
HeaderText"Title" DataField"title"/gt
lt/Columnsgt lt/aspdatagridgt
91
DataGrid Paging
  • When there is too much data to display in one
    screen, a DataGrid can provide automatic paging
  • Set AllowPaging"true"
  • Set PageSize5
  • Handle OnPageIndexChanged event
  • Set page index
  • Fetch data
  • Re-bind data

92
DataGrid Demo
  • Demo DataBinding4.aspx
  • Binding to a database with DataGrid
  • Demo DataBinding5.aspx
  • Paging through data with DataGrid

93
Templates
  • Templates provide a powerful way to customize the
    display of a server control
  • Customize structure not just style
  • Can use controls or other HTML within a template
  • 3rd party controls can expose new templates
  • With data binding, templates specify a set of
    markup (HTML or server controls) for each bound
    piece of data
  • Not just specifying formatting and style for a
    column
  • However, templates are not limited to data
    binding
  • No fixed set of templates
  • Controls may define their own and expose any
    number of them

94
Templates
  • Standard templates for list-bound controls
  • HeaderTemplate rendered once before all data
    bound rows
  • ItemTemplate rendered once for each row in the
    data source
  • AlternatingItemTemplate like ItemTemplate, but
    when present is used for every other row
  • SeparatorTemplate rendered between each row
  • FooterTemplate rendered once, after all data
    bound rows

95
Templates
HeaderTemplate
Templates used in Repeater controls

ItemTemplate
SeparatorTemplate
AlternatingItem-Template
FooterTemplate
96
Data Binding in Templates
  • Templates need to access the bound data
  • Container is an alias for the templates
    containing control
  • DataItem is an alias for the current row of the
    datasource
  • DataBinder.Eval is a utility function provided to
    retrieve and format data within a template

lt DataBinder.Eval(Container.DataItem, "price",
" 0") gt
97
Repeater Control
  • Provides simple output of a list of items
  • No inherent visual form
  • Templates provide the visual form
  • No paging
  • Can provide templates for separators
  • Not updateable

98
Repeater Control
ltaspRepeater id"repList" runat"server"gtlttempla
te name"HeaderTemplate"gt lttablegt
lttrgtlttdgtTitlelt/tdgtlttdgtTypelt/tdgtlt/trgtlt/templategt
lttemplate name"ItemTemplate"gt lttrgt lttdgtlt
DataBinder.Eval(Container.DataItem,"title_id")
gtlt/tdgt lttdgtlt DataBinder.Eval(Container.DataI
tem,"type") gtlt/tdgt lt/trgtlt/templategtlttemplate
name"FooterTemplate"gt lt/tablegtlt/templategtlt/a
spRepeatergt
99
DataList Control
  • Provides list output with editing
  • Default look is a table
  • Customized via templates
  • Directional rendering (horizontal or vertical)
  • Single and multiple selection
  • Alternate item
  • Updateable
  • No paging

100
DataList Control
void Page_Load(object s, EventArgs e)
myDataGrid.DataSource GetSampleData()
myDataGrid.DataBind() ltaspdatalist
id"myDataList" runat"server"gt lttemplate
name"itemtemplate"gt ltbgtTitle idlt/bgt lt
DataBinder.Eval(Container.DataItem, "title_id")
gt ltbrgt ltbgtTitlelt/bgt lt DataBinder.Eval(Con
tainer.DataItem, "title") gt lt/templategt lt/aspd
atalistgt
101
Templates Demo
  • Demo DataBinding6.aspx, DataBinding7.aspx
  • Using templates and data binding to a database
    with DataGrid, Repeater and DataList controls

102
Accessing a Database
9.1
  • ADO.NET Overview

103
Looking Back
  • ODBC (Open Database Connectivity)
  • Interoperability to a wide range of database
    management systems (DBMS)
  • Widely accepted API
  • Uses SQL as data access language
  • DAO (Data Access Objects)
  • Programming interface for JET/ISAM databases
  • ISAM (pronounced "eye sam") stands for Indexed
    Sequential Access Method. It is a technique for
    storing and accessing data in a file on secondary
    storage, for example a disk. ISAM is not a
    stand-alone program it is a library of functions
    that implement an algorithm.
  • Uses automation (ActiveX, OLE automation)
  • RDO (Remote Data Objects)
  • Tighter coupling to ODBC
  • Geared more to client/server databases (vs. DAO)

104
Looking Back
  • OLE DB
  • Broad access to data, relational and other
  • Built on COM
  • Not restricted to SQL for retrieving data
  • Can use ODBC drivers
  • Low-level (C) interface
  • ADO (ActiveX Data Objects)
  • Simple component-based, object-oriented interface
  • Provides a programming model to OLE DB accessible
    outside of C

105
Looking Back
Your Application
ADO
OLE DB
ODBC Provider
Simple Provider
Native Provider
OLE DB Provider
ODBC
OLE DB Provider
ODBC Driver
TextFile
Mainframe
Database
Database
106
Looking Back
  • ADO was designed as a connected, tightly coupled
    model
  • Appropriate for client/server architectures
  • Primarily relational (not hierarchical like XML)
  • Object design is not well factored
  • Too many ways to do the same thing
  • Objects try to do too much
  • Not originally designed for a distributed,
    n-tier environment

107
What Is ADO.NET?
  • ADO .NET is a collection of classes, interfaces,
    structures, and enumerated types that manage data
    access from relational data stores within the
    .NET Framework
  • These collections are organized into namespaces
  • System.Data, System.Data.OleDb,
    System.Data.SqlClient, etc.
  • ADO .NET is an evolution from ADO.
  • Does not share the same object model, but shares
    many of the same paradigms and functionality!

108
ADO.NET Goals
  • Well-factored design
  • Highly scaleable through a robust disconnected
    model
  • Rich XML support (hierarchical as well as
    relational)
  • Data access over HTTP
  • Maintain familiar ADO programming model
  • Keep ADO available via .NET COM interoperability

109
Managed Providers
  • Merges ADO and OLEDB into one layer
  • Each provider contains a set of classes that
    implement common interfaces
  • Initial managed provider implementations
  • ADO Managed Provider provides access to any OLE
    DB data source
  • SQL Server Managed Provider provides optimal
    performance when using SQL Server
  • Exchange Managed Provider retrieve and update
    data in Microsoft Exchange

110
Managed Providers
Your Application
ADO.NET Managed Provider
SQL Managed Provider
ADO Managed Provider
OLE DB Provider
SQL ServerDatabase
Database
111
Data Access Styles
  • Connected Forward-only, read-only
  • Application issues query then reads back results
    and processes them
  • Called as Firehose cursor
  • DataReader object
  • Disconnected
  • Application issues query then retrieves and
    stores results for processing
  • Minimizes time connected to database
  • DataSet object

112
Data Binding
  • Key component of Web Forms framework
  • Flexible and easy to use
  • Bind a controls property to information in any
    type of data store
  • Provides control over how data moves back and
    forth
  • Simple controls for displaying a single value
  • Complex controls for displaying a data structure

ltaspLabel runat"server" Text'lt
CustList(0).FirstName gt'/gt
113
Accessing a Database
9.1
  • ADO.NET Classes

114
IDbConnection Interface
  • Creates a unique session with a data source
  • Implemented by SqlDbConnection and
    OleDbConnection
  • Functionality
  • Open, close connections
  • Begin transactions
  • IDbTransaction provide Commit transactions are
    saved onto the database and Rollback
    transactions are not saved onto the database
    methods
  • Used in conjunction with IDbCommand and
    IDataAdapter objects
  • Additional properties, methods and collections
    depend on the provider

115
IDbCommand Interface
  • Represents a statement to be sent to a data
    source
  • Usually, but not necessarily SQL
  • Implemented by OleDbCommand and SqlCommand
  • Functionality
  • Define statement to execute
  • Execute statement
  • Pass and retrieve parameters
  • Create a prepared (compiled) version of command
  • ExecuteReader returns rows, ExecuteNonQuery
    doesnt, ExecuteScalar returns single value
  • Additional properties, methods and collections
    depend on the provider

116
IDataReader Interface
  • Forward-only, read-only (fire hose) access to a
    stream of data
  • Implemented by SqlDataReader and OleDbDataReader
  • Created via ExecuteReader method of IDbCommand
  • Operations on associated IDbConnection object
    disallowed until reader is closed

117
System.Data.OleDb Namespace
  • Managed provider for use with OLEDB providers
  • SQLOLEDB (SQL Server) use System.Data.SQL
  • MSDAORA (Oracle)
  • JOLT (Jet)
  • OLEDB for ODBC providers
  • OleDbConnection, OleDbCommand and OleDbDataReader
    classes
  • Classes for error handling
  • Classes for connection pooling

118
DataReader Example
string sConnString "ProviderSQLOLEDB.1"
"User IDsaInitial CatalogNorthwind "
"Data SourceMYSERVER" OleDbConnection conn
new OleDbConnection(sConnString) conn.Open() s
tring sQueryString "SELECT CompanyName FROM
Customers" OleDbCommand myCommand new
OleDbCommand(sQueryString, conn) OleDbDataReader
myReader myCommand.ExecuteReader() while
(myReader.Read()) Console.WriteLine(myReader.
GetString(0)) myReader.Close() conn.Close()
119
System.Data Namespace
  • Contains the core classes of the ADO.NET
    architecture
  • Disconnected DataSet is central
  • Supports all types of applications
  • Internet based
  • ASP.NET
  • XML
  • Windows forms based

120
System.Data Namespace
  • Contains classes used by or derived from managed
    providers
  • IDbConnection, IDbCommand, IDbDataReader

121
DataSet
  • A collection of tables
  • Has no knowledge of the source of the data
  • Keeps track of all relationships among tables
  • Rich programming model (has objects for tables,
    columns, relationships, and so on)
  • Remembers original and current state of data
  • Can dynamically modify data and metadata
  • Native serialization format is XML
  • Located in System.Data

122
DataSet
DataSet
DataTable
DataColumn
DataRow
DataRelation
123
System.Data.SqlClient Namespace
  • Managed provider native to SQL Server
  • Built on TDS (Tabular Data Stream is a protocol,
    or a set of rules describing how to transmit data
    between two computers developed by Sybase) for
    high performance in SQL Server
  • SqlConnection, SqlCommand and SqlDataReader
    classes
  • Classes for
  • Error handling
  • Connection pooling (implicitly enabled by default
    ) is a technique used for sharing server
    resources among requesting clients.
  • System.Data.SqlTypes provides classes for native
    SQL Server data types

124
IDataAdapter Interface
  • Populates or sends updates to a DataSet
  • Implemented by OleDbDataAdapter and
    SqlDataAdapter
  • Not connection based
  • Represents an asynchronous approach
  • A superset of a command object
  • Contains four default command objects for Select,
    Insert, Update, and Delete

125
DataSet Example
string sConnString "Persist Security
InfoFalse " "User IDsaInitial
CatalogNorthwind " "Data
SourceMYSERVER" SqlConnection conn new
SqlConnection(sConnString) conn.Open() string
sQueryString "SELECT CompanyName FROM
Customers" SqlDataAdapter myDSAdapter new
SqlDataAdapter() DataSet myDataSet new
DataSet() myDSAdapter.SelectCommand new
SqlCommand(sQueryString, conn) myDSAdapter.Fill(m
yDataSet) conn.Close()
126
DataTable
  • In-memory object representing one table
  • Columns
  • Rows
  • Schema defined by Columns collection
  • Data integrity provided through Constraint
    objects
  • Public events
  • Modifying/deleting rows
  • Modifying columns

127
DataColumn
  • Fundamental building block of a DataTable schema
    (contained in Columns collection)
  • Defines what type of data may be entered (via
    DataType property)
  • Other important properties include AllowNull,
    Unique, and ReadOnly
  • Can contain Constraints (a collection on
    DataTable)
  • Can contain Relations (collection on DataSet)

128
DataRow
  • Represents data in a DataTable (contained in Rows
    collection)
  • Conforms to schema defined by DataColumns
  • Properties for determining row state (e.g., new,
    changed, deleted, etc.)
  • All additions/modifications committed with
    AcceptChanges method of DataTable

129
DataRelation
  • Relates two DataTables via DataColumns
  • DataType value of both DataColumns must be
    identical
  • Updates can be cascaded to child DataTables
  • Modifications that invalidate the relation are
    disallowed

130
Creating a DataSet in Code
  • Create DataSet
  • Define tables

DataSet dataset new DataSet() dataset.DataSetNa
me "BookAuthors" DataTable authors new
DataTable("Author") DataTable books new
DataTable("Book")
131
Creating a DataSet in Code
  • Define columns
  • Define keys

DataColumn id authors.Columns.Add("ID",
typeof(Int32)) id.AutoIncrement
true authors.PrimaryKey new DataColumn
id DataColumn name new
authors.Columns.Add("Name",typeof(String)) DataC
olumn isbn books.Columns.Add("ISBN",
typeof(String)) books.PrimaryKey new
DataColumn isbn DataColumn title
books.Columns.Add("Title", typeof(String)) DataCo
lumn authid books.Columns.Add("AuthID",typeof(In
t32)) DataColumn foreignkey new DataColumn
authid
132
Creating a DataSet in Code
  • Add the tables to the DataSet

dataset.Tables.Add (authors) dataset.Tables.Add
(books)
133
Creating a DataSet in Code
  • Add data and save the DataSet

DataRow shkspr authors.NewRow() shkspr"Name"
"William Shakespeare" authors.Rows.Add(shkspr)
DataRelation bookauth new DataRelation("BookAu
thors", authors.PrimaryKey,
foreignkey) dataset.Relations.Add
(bookauth) DataRow row books.NewRow() row"Au
thID" shkspr"ID" row"ISBN"
"1000-XYZ" row"Title" "MacBeth" books.Rows.A
dd(row) dataset.AcceptChanges()
134
Typed DataSets
  • Typed DataSet
  • Derived from base DataSet class
  • Uses XML schema to generate new class
  • Tables, columns, etc. compiled into new class

ds.Customers.FirstName
  • Untyped DataSet
  • No built-in schema
  • Tables, columns, etc. exposed only as collections

ds.Tables"Customers".Rows0"FirstName"
135
Errors and Exceptions
  • Error class
  • Contains information on an error or warning
    returned by data source
  • Created and managed by Errors class
  • Errors class
  • Contains all errors generated by an adapter
  • Created by Exception class
  • Exception class
  • Created whenever an unhandled error occurs
  • Always contains at least one Error instance

136
Errors and Exceptions Example
try DataTable myTable new DataTable()
myTable.Columns.Add("myCol")
myTable.Columns.Add("myCol") //whoops! catch
(DataException myException) Console.WriteLine
("Message " myException.Message "\n"
"Source " myException.Source "\n"
Stack Trace " myException.StackTrace
"\n")
137
ADO vs. ADO.NET
  • ADO is a slower automation layer over OLE DB for
    use in Visual Basic, etc.
  • ADO.NET provides direct, fast access to data from
    any language
  • ADO.NET essentially has merged OLE DB and ADO
    into a single layer

138
Resources
  • http//msdn.microsoft.com/net/aspnet/default.asp
  • http//www.asp.net/
  • http//www.asptoday.com/
  • http//www.aspfree.com/
  • http//www.devx.com/dotnet/
  • http//msdn.microsoft.com
  • ASP.NET QuickStart Tutorial
  • http//samples.gotdotnet.com/quickstart/aspplus/
  • W3 Schools ASP .NET Tutorial
  • http//www.w3schools.com/aspnet/default.asp
  • Several Online Presentations
Write a Comment
User Comments (0)
About PowerShow.com