Download presentation
Presentation is loading. Please wait.
Published byGwen Goodman Modified over 9 years ago
1
Malek Kemmou Technology Architect, Application Platform Microsoft Middle East and Africa malek@microsoft.com Using Visual Studio 2005 to Build Data- Driven ASP.NET 2.0 Applications
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
DataSource Controls NameDescription SqlDataSourceConnects data-binding controls to 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
5
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 Parameterized operation
6
Using SqlDataSource <asp:SqlDataSource ID="Titles" RunAt="server" ConnectionString="server=localhost;database=pubs;integrated security=true" SelectCommand="select title_id, title, price from titles" />
7
Key SqlDataSource Properties NameDescription ConnectionStringConnection string used to connect to data source SelectCommandCommand used to perform queries InsertCommandCommand used to perform inserts UpdateCommandCommand used to perform updates DeleteCommandCommand used to perform deletes DataSourceModeSpecifies whether DataSet or DataReader is used (default = DataSet) ProviderNameSpecifies provider (default = SQL Server.NET provider)
8
Using an Oracle Database <asp:SqlDataSource ID="Titles" RunAt="server" ConnectionString="..." SelectCommand="select title_id, title, price from titles" ProviderName="System.Data.OracleClient" />
9
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
10
<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
11
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
12
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
13
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
14
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" />
15
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 GO CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers WHERE Country = @Country GO CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country FROM Customers ORDER BY Country GO CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country FROM Customers ORDER BY Country GO
16
SqlDataSource
17
XmlDataSource Declarative data binding to XML data Supports caching and XSL transformations One-way data binding only; no updating
18
Key XmlDataSource Properties NameDescription DataFilePath to file containing XML data TransformFilePath to file containing XSL style sheet EnableCaching XPathXPath expression used to filter data CacheDurationLength of time in seconds data should be cached CacheExpirationPolicySpecifies whether cache duration is sliding or absolute CacheKeyDependencyCreates dependency on specified cache key Specifies whether caching is enabled (default = false)
19
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
20
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
21
Key ODS Properties, Cont. NameDescription InsertParametersSpecifies parameters for InsertMethod UpdateParametersSpecifies parameters for UpdateMethod DeleteParametersSpecifies parameters for DeleteMethod SelectParametersSpecifies parameters for SelectMethod CacheDurationLength of time in seconds data should be cached SqlCacheDependencyCreates dependency on specified database entity
22
Initialization and Clean-Up ObjectDataSource.SelectMethod et al can identify 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
23
ObjectDataSource
24
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
25
GridView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select lastname, firstname, title from employees" />
26
Output
27
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
28
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" >
29
Output
30
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
31
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">
32
Output
33
Master-Detail Views
34
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
35
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 commandUpdate parameters
36
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"
37
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" />
38
Error Detection Controls fire events after database updates –GridView.RowUpdated –DetailsView.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
39
Handling Update Errors <asp:SqlDataSource ID="Employees" RunAt="server"... UpdateCommand="..." OnUpdated="OnUpdateComplete">...... void OnUpdateComplete (Object source, SqlDataDataSourceStatusEventsArgs e) { if (e.Exception != null) { // Exception thrown. Set e.ExceptionHandled to true to prevent // the SqlDataSource from throwing an exception, or leave it set // to false to allow SqlDataSource to rethrow the exception } else if (e.AffectedRows == 0) { // No exception was thrown, but no records were updated, either. // Might want to let the user know that the update failed }
40
Editing with GridViews and DetailsViews
41
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
42
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
43
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
44
Preparing Web.config <add name="Northwind" connectionString="server=localhost;database=northwind;..." />
45
Using SqlCacheDependency with the Application Cache Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products"); Database name Table name
46
Using SqlCacheDependency with the Output Cache <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> Database name Table name
47
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
48
Cache Configuration –Enable/disable application cache –Enable/disable item expiration and more, –Enable/disable output caching –Enable/disable disk-based persistence –Set maximum size per app and more
49
SQL Cache Dependencies
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.