Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Access in ASP.NET 2.0 Bradley Millington Program Manager Web Platform and Tools.

Similar presentations


Presentation on theme: "Data Access in ASP.NET 2.0 Bradley Millington Program Manager Web Platform and Tools."— Presentation transcript:

1 Data Access in ASP.NET 2.0 Bradley Millington Program Manager Web Platform and Tools

2 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) Agenda

3 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)

4 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

5 Database XML Document Data-bound Control Data Source Control Business Object … Data Control Types

6 Binding to Databases with SqlDataSource demo Bradley Millington Program Manager Web Platform and Tools

7 Configured Connection Strings Persistence and declarative referencing of connection- strings from Web.Config –Avoid hard-coding within pages/code –Can be optionally encrypted VS supports at design time –Promote use for best practices –Enable optional encrypting of values in config Flexible Admin Support: –MMC Admin Tool Support –Configuration API Support

8 <connectionStrings> <add name="pubs“ ProviderName=“…” <add name="pubs“ ProviderName=“…” connectionString=“…” /> connectionString=“…” /></connectionStrings> ” SelectCommand=“select au_id from authors” runat=“server”/> ” SelectCommand=“select au_id from authors” runat=“server”/> Web.config: Page.aspx: Dim connstr As String = ConfigurationSettings.ConnectionStrings(“pubs”) Code.vb: Config Connection Strings

9 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 Binding to Objects

10 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

11 Web Page DataSourceID = ObjectDataSource1 Northwind Database OrdersComponent OrderItemsComponent CompaniesComponent <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrders UpdateMethod = UpdateOrder DeleteMethod = DeleteOrder Returns IEnumerable of Orders Order.OrderID Order.OrderName Order.OrderDate Binding to Objects

12 Binding to Objects with ObjectDataSource demo Bradley Millington Program Manager Web Platform and Tools

13 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

14 Under the Hood: Updates, Inserts, Deletes GridView extracts values from input controls, keys from viewstate (DataKeyNames) Dictionaries passed to data source operation –Update: Keys, Values [, OldValues] –Delete: Keys [, OldValues] –Insert: Values Data source applies values as parameters to command or method –Merged with any statically defined parameters –Names of parameter values match selected fields –Can optionally set format string to differentiate Keys, OldValues from new Values: OldValuesParameterFormatString=“original_{0}”

15 ID Name State GridView: DataKeyNames = ID <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = ContactsComponent SelectMethod = GetContact UpdateMethod = UpdateContact Under the Hood: Updates

16 ID0 NameBradley CompanyMicrosoft GridView: DataKeyNames = ID ID0 ViewState GetContact (ID) [Edit] Request.QueryString[“ContactID”] Under the Hood: Updates

17 ID0 NameBrad CompanyMicrosoft UpdateContact (ID, Name, Company) GridView: DataKeyNames = ID ID0 ViewState ID0 Keys NameBrad CompanyMicrosoft Values NameBradley CompanyMicrosoft OldValues [Update] Under the Hood: Updates

18 ID0 NameBradley CompanyMicrosoft GridView: DataKeyNames = ID ID0 ViewState [Edit] UpdateContact (ID, Name, Company, Original_ID) Under the Hood: Updates

19 ID1 NameBrad CompanyMicrosoft UpdateContact (ID, Name, Company, Original_ID) GridView: DataKeyNames = ID ID0 ViewState ID0 Keys ID1 NameBrad CompanyMicrosoft Values NameBradley CompanyMicrosoft OldValues [Update] OldValuesParameterFormatString = “Original_{0}” Under the Hood: Updates

20 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

21 Data Source Events 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.vb Page.aspx

22 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

23 Web Page Northwind Database Northwind Database OrdersComponent OrderItemsComponent CompaniesComponent <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrdersBy Orders.aspx?company=Microsoft Filtering Data

24 Web Page Northwind Database Page Developer API <asp:ObjectDataSource ID = ObjectDataSource2 TypeName = CompaniesComponent SelectMethod = GetCompanies Northwind Database OrdersComponent OrderItemsComponent CompaniesComponent <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrdersBy Filtering Data

25 Web Page Northwind Database Northwind Database OrdersComponent OrderItemsComponent CompaniesComponent <asp:GridView ID = GridView1 AutoGenerateSelectButton = true <asp:ObjectDataSource ID = ObjectDataSource2 TypeName = OrdersComponent SelectMethod = GetOrderBy Master-Details (1 Page)

26 Details Page Northwind Database Northwind Database OrdersComponent OrderItemsComponent CompaniesComponent <asp:GridView ID = GridView1 Master Page <asp:ObjectDataSource ID = ObjectDataSource2 TypeName = OrdersComponent SelectMethod = GetOrderBy Master-Details (2 Page)

27 Filtering and Master-Details demo Bradley Millington Program Manager Web Platform and Tools

28 Data Binding In Templates V1 data binding syntax too verbose – Simplified data binding syntax in ASP.NET 2.0 – // 1-way databinding – // 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)

29 Data Binding in Templates demo Bradley Millington Program Manager Web Platform and Tools

30 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 Can also manage caching yourself in business object layer

31 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”

32 Data Source Caching demo Bradley Millington Program Manager Web Platform and Tools

33 Hierarchical Data Hierarchical data sources –Expose data as parent-child relationships – Hierarchical data-bound controls –Use a navigator to walk the tree structure – Can also bind tabular (list) controls to hierarchical data –Only top-level data items are rendered

34 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

35 Binding to Hierarchical Data demo Bradley Millington Program Manager Web Platform and Tools

36 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

37 Resources My Slides and Demos –http://www.bradmi.net/presentationshttp://www.bradmi.net/presentations ASP.NET 2.0 Quickstarts –http://www.asp.net/quickstarthttp://www.asp.net/quickstart ASP.NET Forums –http://www.asp.net/forumshttp://www.asp.net/forums Nikhil Kothari's Blog –http://www.nikhilk.nethttp://www.nikhilk.net

38


Download ppt "Data Access in ASP.NET 2.0 Bradley Millington Program Manager Web Platform and Tools."

Similar presentations


Ads by Google