* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download What's New with Visual Studio 2005 and ASP.NET 2.0
Survey
Document related concepts
Oracle Database wikipedia , lookup
Microsoft Access wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Concurrency control wikipedia , lookup
Team Foundation Server wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Relational model wikipedia , lookup
Clusterpoint wikipedia , lookup
Transcript
Session 3 - Leveraging Data in ASP.NET 2.0 (Level 200) Philip Wolfe Senior Consultant Sogeti Agenda Simplified data binding Data source controls Data controls GridView and DetailsView controls Editing with GridView and DetailsView Caching SQL cache dependencies Cache configuration Simplified Data Binding Data binding expressions are now simpler and support hierarchical (XML) data binding <!-- ASP.NET 1.x data binding expression --> <%# DataBinder.Eval (Container.DataItem, "Price") %> <!-- Equivalent ASP.NET 2.0 data binding expression --> <%# Eval ("Price") %> <!-- XML data binding --> <%# XPath ("Price") %> <%# XPathSelect ("Price") %> <!-- Two-Way data binding --> <%# Bind ("Price") %> Simplified Data Binding Data binding code has changed as well //C# - version 1.x DataGrid1.DataSource = ProductsDataSet; DataGrid1.DataBind(); //C# - version 2.0 // It can all be done declaratively (in the aspx file) DataSource Controls Declarative (no-code) data binding Name Description SqlDataSource Connects data-binding controls to SQL databases AccessDataSource Connects data-binding controls to Access databases XmlDataSource Connects data-binding controls to XML data ObjectDataSource Connects data-binding controls to data components SiteMapDataSource Connects site navigation controls to site map data 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 Using SqlDataSource SQL Server <asp:SqlDataSource ID="Titles" RunAt="server" ConnectionString="server=localhost;database=pubs;integrated security=true" SelectCommand="select title_id, title, price from titles" /> <asp:DataGrid DataSourceID="Titles" RunAt="server" /> Best Practice using web.config <asp:SqlDataSource ID="Authors" RunAt=" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" /> Oracle <asp:SqlDataSource ID="Titles" RunAt="server" ConnectionString="..." SelectCommand="select title_id, title, price from titles" ProviderName="System.Data.OracleClient" /> SqlDataSource and Caching SqlDataSource supports declarative caching of results through these properties: Name Description EnableCaching Specifies whether caching is enabled (default = false) CacheDuration Length of time in seconds results should be cached CacheExpirationPolicy Specifies whether cache duration is sliding or absolute CacheKeyDependency Creates dependency on specified cache key SqlCacheDependency Creates dependency on specified database entity Caching Query Results <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" /> 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 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 XxxParameters Properties Name Description SelectParameters Specifies parameters for SelectCommand InsertParameters Specifies parameters for InsertCommand UpdateParameters Specifies parameters for UpdateCommand DeleteParameters Specifies parameters for DeleteCommand FilterParameters Specifies parameters for FilterExpression XxxParameter Types Name Description Parameter Binds a replaceable parameter to a data field ControlParameter Binds a replaceable parameter to a control property CookieParameter Binds a replaceable parameter to a cookie value FormParameter Binds a replaceable parameter to a form field QueryStringParameter Binds a replaceable parameter to a query string parameter SessionParameter Binds a replaceable parameter to a session variable 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"> <SelectParameters> <asp:ControlParameter Name="Country" ControlID="MyDropDownList" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> <asp:DataGrid DataSourceID="Customers" RunAt="server" /> 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"> <SelectParameters> <asp:ControlParameter Name="Country" ControlID="MyDropDownList" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> <asp:DataGrid DataSourceID="Customers" RunAt="server" /> CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country FROM Customers ORDER BY Country CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers WHERE Country = @Country SqlDataSource Creating a SqlDataSource with a SQL stmt. Binding to a DropDownList Caching a DataSource Creating a SqlDataSource with a parameter Filtering a GridView 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 Key ODS Properties Name Description TypeName Type name of data component SelectMethod Method called on data component to perform queries InsertMethod Method called on data component to perform inserts UpdateMethod Method called on data component to perform updates DeleteMethod Method called on data component to perform deletes EnableCaching Specifies whether caching is enabled (default = false) 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 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 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 <Columns> element Highly customizable UI GridView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select lastname, firstname, title from employees" /> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" /> Output GridView Field Types Name Description BoundField Renders columns of text from fields in data source ButtonField Renders columns of buttons (push button, image, or link) CheckBoxField Renders Booleans as check boxes CommandField Renders controls for selecting and editing GridView data HyperLinkField Renders columns of hyperlinks ImageField Renders columns of images TemplateField Renders columns using HTML templates 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" > <Columns> <asp:ImageField HeaderText="" DataField="photo" /> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <%# Eval ("firstname") + " " + Eval ("lastname") %> </ItemTemplate> </asp:TemplateField> <asp:BoundField HeaderText="Title" DataField="title" /> </Columns> </asp:GridView> Output GridView Control Enable Paging Enable Sorting Remove some columns Change alignment Add Formatting Create a Hyperlink Column 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 <Fields> element Highly customizable UI 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"> <Fields> <asp:ImageField HeaderText="" DataField="photo" /> <asp:BoundField HeaderText="Employee ID" DataField="employeeid" /> <asp:BoundField HeaderText="Date Hired" DataField="hiredate" /> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <%# Eval ("firstname") + " " + Eval ("lastname") %> </ItemTemplate> </asp:TemplateField> <asp:BoundField HeaderText="Title" DataField="title" /> </Fields> </asp:DetailsView> Output DetailsView Control Create a datasource that selects a single row Enable Edit, Delete, and Insert 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 Editing with GridViews Update command Update parameters <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"> <UpdateParameters> <asp:Parameter Name="EmployeeID" Type="Int32" /> <asp:Parameter Name="lastname" Type="String" /> <asp:Parameter Name="firstname" Type="String" /> </UpdateParameters> </asp:SqlDataSource> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" DataKeyNames="EmployeeID" AutoGenerateEditButton="true" /> Primary key Edit buttons 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" 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"> <UpdateParameters> <asp:Parameter Name="EmployeeID" Type="Int32" /> <asp:Parameter Name="lastname" Type="String" /> <asp:Parameter Name="firstname" Type="String" /> </UpdateParameters> </asp:SqlDataSource> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" DataKeyNames="EmployeeID" AutoGenerateEditButton="true" /> 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 SQL Cache Dependencies New cache dependency type Embodied in SqlCacheDependency class Configured through <sqlCacheDependency> configuration section Links cached items to database entities ASP.NET application cache ASP.NET output cache Compatible with SQL Server 7, 2000, 2005 Preparing a Database Use Aspnet_regsql.exe or SqlCacheDependencyAdmin to prepare database* aspnet_regsql -S localhost -E -d Northwind -ed Server name Trusted connection Database name Enable database * Not necessary for SQL Server 2005 Preparing a Table Use Aspnet_regsql.exe or SqlCacheDependencyAdmin to prepare table* aspnet_regsql -S localhost -E -d Northwind -t Products -et Server name Trusted connection Database name Table name Enable table * Not necessary for SQL Server 2005 Preparing Web.config <configuration> <connectionStrings> <add name="NorthwindConnectionString" connectionString="server=localhost;database=northwind;..." /> </connectionStrings> <system.web> <caching> <sqlCacheDependency enabled="true" pollTime=“60000"> <databases> <add name="Northwind" connectionStringName="NorthwindConnectionString" /> </databases> </sqlCacheDependency> </caching> <system.web> </configuration> Using SqlCacheDependency with the Application Cache Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products"); Database name Table name Using SqlCacheDependency with the Output Cache <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> Database name Table name 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 SQL Cache Dependencies Prepare Database Prepare Table Create a cache section Enable Caching Enable SqlCacheDependency Summary New DataSource Controls New Data UI Controls Caching, Paging, Sorting, Editing with minimal coding Thank You Philip Wolfe [email protected] www.philipwolfe.com © 2003-2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.