* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download asp:ObjectDataSource ID
Survey
Document related concepts
Transcript
Data Access in ASP.NET 2.0 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 <asp:GridView <asp:TreeView DataSourceId=“MySource” runat=“server”/> runat=“server”> … Data Source Control <asp:XmlDataSource <asp:ObjectDataSource <asp:SqlDataSource Id=“MySource” DataFile=“Bookstore.xml” TypeName=“CustomersDB” ConnectionString=“…” XPath=“/bookstore/book[@genre=‘fiction’]” SelectMethod=“GetCustomersByRegion” SelectCommand=“select id from authors” runat=“server” /> Database Business Object XML Document 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 <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrders UpdateMethod = UpdateOrder DeleteMethod = DeleteOrder DataSourceID = ObjectDataSource1 Returns IEnumerable of Orders • Order.OrderID • 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?company=Microsoft OrdersComponent Web Page <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent OrderItemsComponent SelectMethod = GetOrdersBy <SelectParameters> CompaniesComponent <asp:QueryStringParameter Name=“companyName” Northwind QueryStringField=“company”/> Database </SelectParameters> Filtering Data Web Page <asp:ObjectDataSource ID = ObjectDataSource2 TypeName = CompaniesComponent SelectMethod = GetCompanies OrdersComponent Developer API <asp:ObjectDataSource ID = Page ObjectDataSource1 TypeName = OrdersComponent OrderItemsComponent SelectMethod = GetOrdersBy <SelectParameters> CompaniesComponent <asp:ControlParameter Name= companyName Northwind ControlID= DropDownList1 /> Database </SelectParameters> Master-Details (1 Page) Web Page <asp:GridView ID = GridView1 AutoGenerateSelectButton = true OrdersComponent <asp:ObjectDataSource ID = ObjectDataSource2 TypeName = OrdersComponent OrderItemsComponent SelectMethod = GetOrderBy <SelectParameters> <asp:ControlParameter CompaniesComponent Name= orderID Northwind ControlID= GridView1 /> Database </SelectParameters> Master-Details (2 Page) Master Page Details Page <asp:GridView ID = GridView1 <ColumnFields> <asp:HyperLinkField … /> </ColumnFields> OrdersComponent <asp:ObjectDataSource ID = ObjectDataSource2 TypeName = OrdersComponent OrderItemsComponent SelectMethod = GetOrderBy <SelectParameters> <asp:QueryStringParameter CompaniesComponent Name= orderID Northwind QueryStringField= ID /> Database </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