Data Access in Aspnet 2
Data Access in Aspnet 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
<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
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
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: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
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
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
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
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