Presentation is loading. Please wait.

Presentation is loading. Please wait.

Philip Wolfe Senior Consultant Sogeti Session 3 - Leveraging Data in ASP.NET 2.0 (Level 200)

Similar presentations


Presentation on theme: "Philip Wolfe Senior Consultant Sogeti Session 3 - Leveraging Data in ASP.NET 2.0 (Level 200)"— Presentation transcript:

1 Philip Wolfe Senior Consultant Sogeti Session 3 - Leveraging Data in ASP.NET 2.0 (Level 200)

2 Agenda Simplified data binding Data source controls Data controls GridView and DetailsView controls Editing with GridView and DetailsView Caching SQL cache dependencies Cache configuration

3 Simplified Data Binding Data binding expressions are now simpler and support hierarchical (XML) data binding

4 Simplified Data Binding Data binding code has changed as well //C# - version 2.0 // It can all be done declaratively (in the aspx file) //C# - version 1.x DataGrid1.DataSource = ProductsDataSet; DataGrid1.DataBind();

5 DataSource Controls NameDescription SqlDataSourceConnects data-binding controls to SQL databases AccessDataSourceConnects data-binding controls to Access databases XmlDataSourceConnects data-binding controls to XML data ObjectDataSource Connects data-binding controls to data components SiteMapDataSourceConnects site navigation controls to site map data Declarative (no-code) data binding

6 SqlDataSource Declarative data binding to SQL databases Any database served by a managed provider Two-way data binding SelectCommand defines query semantics InsertCommand, UpdateCommand, and DeleteCommand define update semantics Optional caching of query results Can call stored procedures or use SQL Parameterized operation

7 Using SqlDataSource <asp:SqlDataSource ID="Titles" RunAt="server" ConnectionString="server=localhost;database=pubs;integrated security=true" SelectCommand="select title_id, title, price from titles" /> <asp:SqlDataSource ID="Titles" RunAt="server" ConnectionString="..." SelectCommand="select title_id, title, price from titles" ProviderName="System.Data.OracleClient" /> SQL Server Oracle Best Practice using web.config " />

8 SqlDataSource and Caching SqlDataSource supports declarative caching of results through these properties: NameDescription EnableCachingSpecifies whether caching is enabled (default = false) CacheDurationLength of time in seconds results should be cached CacheExpirationPolicySpecifies whether cache duration is sliding or absolute CacheKeyDependencyCreates dependency on specified cache key SqlCacheDependencyCreates dependency on specified database entity

9 <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select distinct country from customers order by country" EnableCaching="true" CacheDuration="60" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> Caching Query Results Notes: EnableCaching must be true (not default) CacheDuration must be greater than zero DataSourceMode must be DataSet (default) The data is cached in the application cache

10 Parameterized Commands XxxParameters properties permit database commands to be parameterized Example: Get value for WHERE clause in SelectCommand from query string parameter or item selected in drop-down list Example: Get value for WHERE clause in DeleteCommand from GridView XxxParameter types specify source of parameter values

11 XxxParameters Properties NameDescription SelectParametersSpecifies parameters for SelectCommand InsertParameters UpdateParameters DeleteParameters FilterParametersSpecifies parameters for FilterExpression Specifies parameters for InsertCommand Specifies parameters for UpdateCommand Specifies parameters for DeleteCommand

12 XxxParameter Types NameDescription ControlParameterBinds a replaceable parameter to a control property CookieParameterBinds a replaceable parameter to a cookie value FormParameterBinds a replaceable parameter to a form field QueryStringParameterBinds a replaceable parameter to a query string parameter SessionParameterBinds a replaceable parameter to a session variable ParameterBinds a replaceable parameter to a data field

13 Using ControlParameter <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select distinct country from customers order by country" /> <asp:SqlDataSource ID="Customers" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select * from customers where country=@Country"> <asp:ControlParameter Name="Country" ControlID="MyDropDownList" PropertyName="SelectedValue" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" />

14 Calling Stored Procedures <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCountries" /> <asp:SqlDataSource ID="Customers" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCustomers"> <asp:ControlParameter Name="Country" ControlID="MyDropDownList" PropertyName="SelectedValue" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers WHERE Country = @Country CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers WHERE Country = @Country CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country FROM Customers ORDER BY Country CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country FROM Customers ORDER BY Country

15 SqlDataSource Creating a SqlDataSource with a SQL stmt. Binding to a DropDownList Caching a DataSource Creating a SqlDataSource with a parameter Filtering a GridView

16 ObjectDataSource Declarative binding to data components Leverage middle-tier data access components Keep data access code separate from UI layer Two-way data binding SelectMethod, InsertMethod, UpdateMethod, and DeleteMethod Optional caching of query results Parameterized operation

17 Key ODS Properties NameDescription TypeNameType name of data component SelectMethodMethod called on data component to perform queries InsertMethod UpdateMethod DeleteMethod EnableCachingSpecifies whether caching is enabled (default = false) Method called on data component to perform inserts Method called on data component to perform updates Method called on data component to perform deletes

18 Initialization and Clean-Up ObjectDataSource can target static methods or instance methods If instance methods are used: ODS creates new class instance on each call Class must have public default constructor Use ObjectCreated and ObjectDisposing events to perform specialized initialization or clean-up work on data components

19 ObjectDataSource Create a data access object Create an ObjectDataSource specifying the Type, SelectMethod Create a data access object, Take 2 Create a data access object, Take 3

20 The GridView Control Enhanced DataGrid control Renders sets of records as HTML tables Built-in sorting, paging, selecting, updating, and deleting support Supports rich assortment of field types, including ImageFields and CheckBoxFields Declared in element Highly customizable UI

21 GridView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select lastname, firstname, title from employees" />

22 Output

23 GridView Field Types NameDescription BoundFieldRenders columns of text from fields in data source ButtonFieldRenders columns of buttons (push button, image, or link) CheckBoxFieldRenders Booleans as check boxes HyperLinkFieldRenders columns of hyperlinks TemplateFieldRenders columns using HTML templates CommandFieldRenders controls for selecting and editing GridView data ImageFieldRenders columns of images

24 Specifying Field Types <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select photo, lastname, firstname, title from employees" /> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" AutoGenerateColumns="false" >

25 Output

26 GridView Control Enable Paging Enable Sorting Remove some columns Change alignment Add Formatting Create a Hyperlink Column

27 The DetailsView Control Renders individual records Pair with GridView for master-detail views Or use without GridView to display individual records Built-in paging, inserting, updating, deleting Uses same field types as GridView Declared in element Highly customizable UI

28 DetailsView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select employeeid, photo,... from employees" /> <asp:DetailsView DataSourceID="Employees" RunAt="server" AllowPaging="true" AutoGenerateRows="false" PagerSettings-Mode="NextPreviousFirstLast">

29 Output

30 DetailsView Control Create a datasource that selects a single row Enable Edit, Delete, and Insert

31 Inserting, Updating, and Deleting Data controls supply editing UIs AutoGenerateXxxButton properties Insert/EditRowStyle properties Data source controls supply editing logic Insert/Update/DeleteCommand properties Insert/Update/DeleteParameters properties Inserting/ed, Updating/ed, Deleting/ed events Visual Studio supplies the glue

32 Editing with GridViews <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select employeeid, lastname, firstname, from employees" UpdateCommand="update employees set lastname=@lastname, firstname= @firstname where employeeid=@original_employeeid"> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" DataKeyNames="EmployeeID" AutoGenerateEditButton="true" /> Edit buttonsPrimary key Update command Update parameters

33 Conflict Detection First-in wins Update fails if data has changed Structure UpdateCommand accordingly Set ConflictDetection="CompareAllValues" Last-in wins Update succeeds even if data has changed Structure UpdateCommand accordingly Set ConflictDetection="OverwriteChanges"

34 First-In-Wins Updates <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select employeeid, lastname, firstname, from employees" UpdateCommand="update employees set lastname=@lastname, firstname= @firstname where employeeid=@original_employeeid and lastname= @original_lastname and firstname=@original_firstname" ConflictDetection="CompareAllValues"> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" DataKeyNames="EmployeeID" AutoGenerateEditButton="true" />

35 Error Detection Controls fire events after database updates GridView.RowUpdatedDetailsView.ItemUpdated SqlDataSource.Updated, etc. Event handlers receive "status" objects Reveal whether database exception occurred Allow exceptions to be handled or rethrown Reveal how many rows were affected

36 SQL Cache Dependencies New cache dependency type Embodied in SqlCacheDependency class Configured through configuration section Links cached items to database entities ASP.NET application cache ASP.NET output cache Compatible with SQL Server 7, 2000, 2005

37 Preparing a Database Use Aspnet_regsql.exe or SqlCache- DependencyAdmin to prepare database* aspnet_regsql -S localhost -E -d Northwind -ed Trusted connection Database name Enable database * Not necessary for SQL Server 2005 Server name

38 Preparing a Table Use Aspnet_regsql.exe or SqlCache- DependencyAdmin to prepare table* aspnet_regsql -S localhost -E -d Northwind -t Products -et Trusted connection Database name Table name Server name Enable table * Not necessary for SQL Server 2005

39 Preparing Web.config <add name="NorthwindConnectionString" connectionString="server=localhost;database=northwind;..." /> <add name="Northwind" connectionStringName="NorthwindConnectionString" />

40 Using SqlCacheDependency with the Application Cache Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products"); Database name Table name

41 Using SqlCacheDependency with the Output Cache <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> Database name Table name

42 Using SqlCacheDependency with SqlDataSource <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select distinct country from customers order by country" EnableCaching="true" CacheDuration="60000" SqlCacheDependency="Northwind:Customers" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> Database name Table name

43 SQL Cache Dependencies Prepare Database Prepare Table Create a cache section Enable Caching Enable SqlCacheDependency

44 Summary New DataSource Controls New Data UI Controls Caching, Paging, Sorting, Editing with minimal coding

45 Thank You Philip Wolfe pwolfe@funwith.netwww.philipwolfe.com

46 © 2003-2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary. Microsoft


Download ppt "Philip Wolfe Senior Consultant Sogeti Session 3 - Leveraging Data in ASP.NET 2.0 (Level 200)"

Similar presentations


Ads by Google