0% found this document useful (0 votes)
16 views30 pages

Data Access in Aspnet 2

The document discusses data access in ASP.NET 2.0, highlighting the improvements over version 1, including a declarative model for data binding and simplified data manipulation. It covers various data source controls, binding to databases and business objects, and features like caching, filtering, and hierarchical data support. The presentation emphasizes the ease of building rich data-driven applications using Visual Web Developer and SQL Server Express.

Uploaded by

rogitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views30 pages

Data Access in Aspnet 2

The document discusses data access in ASP.NET 2.0, highlighting the improvements over version 1, including a declarative model for data binding and simplified data manipulation. It covers various data source controls, binding to databases and business objects, and features like caching, filtering, and hierarchical data support. The presentation emphasizes the ease of building rich data-driven applications using Visual Web Developer and SQL Server Express.

Uploaded by

rogitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Data Access in ASP.NET 2.

Bradley Millington
Program Manager
Web Platform and Tools
Agenda
• Visual Web Developer 2005 & SQL Server 2005
– All you need to build rich data-driven apps!
– Free Express Editions of both products
• ASP.NET Data Controls
– Enable declarative data binding in ASP.NET 2.0
• Scenarios Covered
– Creating and connecting to a database in VS
– Selecting and displaying data in a web page
– Sorting, paging, updating, deleting, inserting data
– Caching, filtering, master-details, parameters
– Binding to business objects (DAL, BLL)
– Data binding in custom templated UI
– Hierarchical data (XML, SiteMap)
ASP.NET 2.0 and Data Controls
• Data access/presentation too hard in ASP.NET V1
– No declarative model for data acquisition/manipulation
– Common scenarios required 100s of lines of code
• 2.0 provides easy and powerful declarative model
– Handle stateless Web model for data scenarios
– Do not require developer to be aware of page lifecycle events
– Enable rich and pluggable data access storage providers
• Common UI scenarios with little to zero code
– Selecting and displaying data
– Sorting, paging, caching data
– Updating, inserting, deleting data
– Filtering, master-details (parameterization)
ASP.NET 2.0 and Data Controls
• Data Source Controls
– Non-UI controls (no rendering)
– Represent different backend data sources
• Databases, Business Objects, XML, or Web Services
– Can cache, sort, page, filter, update, delete, insert data
– Expose data through tabular or hierarchical interfaces
• Data-bound Controls
– UI controls to render data
• GridView, DetailsView, FormView, TreeView, Menu
– Auto-bind to data exposed from a data source
– Fetches data at the appropriate time in lifecycle
– Can take advantage of data source capabilities
Data Control Types
Data-bound
Control Database
<asp:GridView
<asp:TreeView
DataSourceId=“MySource”
runat=“server”/>
runat=“server”> …

Business
Object
Data Source
Control
<asp:XmlDataSource
<asp:ObjectDataSource
<asp:SqlDataSource
Id=“MySource” XML
DataFile=“Bookstore.xml”
TypeName=“CustomersDB”
ConnectionString=“…” Document
XPath=“/bookstore/book[@genre=‘fiction’]”
SelectMethod=“GetCustomersByRegion”
SelectCommand=“select id from authors”
runat=“server” />
demo

Binding to Databases with


SqlDataSource
Bradley Millington
Program Manager
Web Platform and Tools
Binding to Objects
• Most applications encapsulate data logic from
presentation layer as a best practice
– Embedding SQL code in a page is not ideal
• ObjectDataSource enables declarative binding to
middle-tier objects
– Select, update, insert, delete, filter and cache data
– Supports custom paging and sorting

<asp:ObjectDataSource
Id=“MySource”
TypeName=“CustomersDB”
SelectMethod=“GetCustomers”
UpdateMethod=“UpdateCustomer”
DeleteMethod=“DeleteCustomer”
InsertMethod=“InsertCustomer”
runat=“server” />
Binding to Objects
• Select method can return any Object
or IEnumerable list, collection, or array
• GetProducts() -> ProductCollection
• GetProductsDataSet() -> DataSet
• GetProduct (int productId) -> Product

• Update, Insert, Delete methods


take individual fields or data item object
• UpdateProduct (int id, String name, double price, bool inStock)
• UpdateProduct (Product p) // p.Name, p.Price, p.InStock …
• DeleteProduct (int id)

• Property or parameter names must match selected fields


for GridView/DetailsView automatic
updates/deletes/inserts
Binding to Objects
Web Page

DataSourceID = <asp:ObjectDataSource
ObjectDataSource1 ID = ObjectDataSource1
TypeName = OrdersComponent
Returns IEnumerable of SelectMethod = GetOrders
Orders UpdateMethod = UpdateOrder
• Order.OrderID DeleteMethod = DeleteOrder
• Order.OrderName
• Order.OrderDate

OrderItemsComponent

OrdersComponent CompaniesComponent
Northwind
Database
demo

Binding to Objects with


ObjectDataSource
Bradley Millington
Program Manager
Web Platform and Tools
Data Source Paging
• Previous example does paging in UI layer
– ObjectDataSource returns all data rows
– GridView performs paging by rendering subset of rows
• Paging also supported on data source interface
– Select (int startRowIndex, int maxRows)
– Can be implemented in user-defined stored proc or custom
method
• Data-bound controls (e.g., GridView) can use data
source paging, if supported by data source
– Don’t need to page in the UI layer
– Useful (required) for large amounts of data
Programmability And Events
• Creating, Created
– Raised before/after object instantiated
– Can assign to ObjectInstance
• Selecting, Filtering, Updating, Deleting, Inserting
– Raised before operation
– Can optionally cancel event
– Can validate and manipulate parameters
• Selected, Updated, Inserted, Deleted
– Raised after operation complete
– Can check and handle exceptions
– Can obtain return values and out params
• Disposing
– Raised prior to releasing object
– Dispose() will be called if object implements IDisposable
– Can optionally cancel
Data Source Events
Page.aspx.vb

Sub MySource_Selecting(ByVal sender As Object,


ByVal e As SqlDataSourceCommandEventArgs)
Dim cmd As System.Data.SqlClient.SqlCommand = e.Command
cmd.Parameters(“UserId”).Value = User.Identity.Name
End Sub

Page.aspx

<asp:SqlDataSource ID=“MySource” …
OnSelecting=“MySource_Selecting”
SelectCommand=“sp_GetUserPreferences”
runat=“server”/>
Filtering and Master-Details
• Select Method or Command may be parameterized
• GetCustomersByCountry (int countryCode) -> CustomersCollection
• GetOrdersForCustomer (String customerId) -> OrdersCollection
• GetProduct (int productId) -> Product
• Data source parameter collections enable declarative
associations to values
– QueryStringParameter
– ControlParameter
– SessionParameter
– FormParameter
– CookieParameter
– ProfileParameter
– Static Parameter
Filtering Data
Orders.aspx? Web Page
company=Microsoft

<asp:ObjectDataSource ID =
ObjectDataSource1
OrderItemsComponent
TypeName = OrdersComponent
SelectMethod = GetOrdersBy
OrdersComponent <SelectParameters> CompaniesComponent
<asp:QueryStringParameter
Northwind
Name=“companyName”
Database
QueryStringField=“company”/>
</SelectParameters>
Filtering Data
Web Page

<asp:ObjectDataSource
ID = ObjectDataSource2
TypeName =
CompaniesComponent
SelectMethod = GetCompanies

<asp:ObjectDataSource IDPage = Developer


ObjectDataSource1
API
OrderItemsComponent
TypeName = OrdersComponent
SelectMethod = GetOrdersBy
OrdersComponent <SelectParameters> CompaniesComponent
<asp:ControlParameter
Northwind
Name= companyName
Database
ControlID= DropDownList1 />
</SelectParameters>
Master-Details (1 Page)
Web Page

<asp:GridView ID = GridView1
AutoGenerateSelectButton = true

<asp:ObjectDataSource ID =
ObjectDataSource2
OrderItemsComponent
TypeName = OrdersComponent
SelectMethod = GetOrderBy
OrdersComponent <SelectParameters> CompaniesComponent
<asp:ControlParameter
Name= orderID
Northwind
Database
ControlID= GridView1 />
Master-Details (2 Page)
Master Page Details Page

<asp:GridView ID = GridView1
<ColumnFields>
<asp:HyperLinkField … />
</ColumnFields>

<asp:ObjectDataSource ID =
ObjectDataSource2
OrderItemsComponent
TypeName = OrdersComponent
SelectMethod = GetOrderBy
OrdersComponent <SelectParameters> CompaniesComponent
<asp:QueryStringParameter
Name= orderID
Northwind
Database
QueryStringField= ID />
</SelectParameters>
demo

Filtering and Master-Details

Bradley Millington
Program Manager
Web Platform and Tools
Data Binding In Templates
• V1 data binding syntax too verbose
– <%# DataBinder.Eval(Container.DataItem, “field”
[,formatString]) %>
• Simplified data binding syntax in ASP.NET 2.0
– <%# Eval(“field” [,formatString]) %> // 1-way databinding
– <%# Bind(“field” [,formatString]) %> // 2-way databinding
• New two-way data binding syntax
– Enables templated controls to retrieve input values,
passed to automatic updates, inserts, deletes
– Supported in GridView, DetailsView controls (TemplateField)
– Support in new FormView control (fully-templated DetailsView)
– Not supported for DataList (V1 control)
demo

Data Binding in Templates

Bradley Millington
Program Manager
Web Platform and Tools
Caching Data
• Caching is a best practice, but many developers
don’t do this – it’s too hard in V1!
• Data sources can automatically cache data
– Manages cache key and dependencies for you
– Completely transparent to data-bound controls
<asp:ObjectDataSource …
EnableCaching=“true”
CacheDuration=“[time in seconds]”
CacheExpirationPolicy=“[absolute|sliding]”
CacheKeyDependency=“Customers”
SelectMethod=“GetCustomers”
TypeName=“CustomersDB”
runat=“server” />
• Can also manage caching yourself in business
object layer
SQL Cache Invalidation
• Retains cache entry until database table changes
– Only invalidates when backend data is stale
• Built on SQL Server 2005 notifications
– Supported on SQL7, SQL2k, or SQL Express via polling
• Enabled with SqlCacheDependency property on
OutputCache directive and data source controls
– SqlDataSource supports notifications or polling
– ObjectDataSource supports polling only
• Can use still use notifications in DAL/BLL code

<asp:SqlDataSource …
EnableCaching=“true”
CacheDuration=“Infinite”
SqlCacheDependency=
“conn:table|CommandNotification”
demo

Data Source Caching

Bradley Millington
Program Manager
Web Platform and Tools
Hierarchical Data
• Hierarchical data sources
– Expose data as parent-child relationships
– <asp:XmlDataSource/>
– <asp:SiteMapDataSource/>
• Hierarchical data-bound controls
– Use a navigator to walk the tree structure
– <asp:TreeView/>
– <asp:Menu/>
• Can also bind tabular (list) controls to hierarchical
data
– Only top-level data items are rendered
Hierarchical Data
• Can also bind to XML in a template
– Can bind anywhere in the hierarchy
• New XPath databinding syntax
– XPath(“books/genre/@name”)
– Returns simple value, e.g., “Fiction”
• New XPathSelect syntax
– XPathSelect(“books/genre[@name=‘Fiction’]”)
– Returns a list, e.g., IEnumerable of book elements
– Can be enumerated directly, or bound to the
DataSource property of a list control
demo

Binding to Hierarchical Data

Bradley Millington
Program Manager
Web Platform and Tools
Summary
• Visual Web Developer Express and SQL Server
Express make it easy to build data-driven apps!
• ASP.NET 2.0 data source controls dramatically
simplify data-binding over v1.x
• Integrates easily with middle-tier data
components and business objects
• Retains the flexibility of v1.x for complex
scenarios requiring code
• Provides a model that third-party data providers
can easily extend
Resources
• My Slides and Demos
– http://www.bradmi.net/presentations
• ASP.NET 2.0 Quickstarts
– http://www.asp.net/quickstart
• ASP.NET Forums
– http://www.asp.net/forums
• Nikhil Kothari's Blog
– http://www.nikhilk.net

You might also like