Download presentation
Presentation is loading. Please wait.
Published byEsther Moody Modified over 9 years ago
1
WEB325 Building Data-Driven Web Sites in ASP.NET 2.0 Rob Howard rhoward@telligent.com Telligent Corporation
3
Contact and Slides Rob Howard rhoward@telligent.comwww.telligent.comTelligent.NET Software Development Company Builds Community Server (communityserver.org) Download Slides & Demos www.rob-howard.net Will be posted ASAP
4
Review: ASP.NET 1.X ASP.NET 1.X Introduced data controls Introduced data binding concepts Working with data in ASP.NET 1.X Easy and simple Too much code still required though ASP.NET 2.0 Specifically addresses common scenarios Makes working with data even easier
5
Agenda Safer connection string storage Data binding gets easier Declarative data binding Working with the new data controls Caching data
6
Connection String Storage Persistence and declarative referencing Stored in *.config Avoid hard-coding within pages/code Can be optionally encrypted Built-in design time support Promote use for best practices Enable optional encrypting of values in config Admin Support MMC Admin Tool Support Configuration API Support
7
Config Connection Strings <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:
8
Connection Strings
9
Data Binding Gets Easier Expressions are cleaner Support hierarchical (XML) data binding
10
Declarative Data Binding Controls bound at appropriate time Wire-up done through properties Page lifecycle knowledge not required NameDescription SqlDataSourceConnects data-binding controls to SQL databases AccessDataSourceConnects data-binding controls to Access databases XmlDataSourceConnects data-binding controls to XML data ObjectDataSourceConnects data-binding controls to data components SiteMapDataSourceConnects site navigation controls to site map data
11
SqlDataSource Data binding to SQL Database Microsoft SQL Server, Oracle, DB2, etc. Two-way data binding supported SelectCommand InsertCommand, UpdateCommand, and DeleteCommand Optional caching of query results Parameterized operation
12
Using SqlDataSource <asp:SqlDataSource ID="Titles" ConnectionString=" " RunAt="server“ SelectCommand="select title_id, title, price from titles" /> ID="Titles" ConnectionString=" " RunAt="server“ SelectCommand="select title_id, title, price from titles" /><asp:DataGridDataSourceID="Titles" RunAt="server" />
13
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)
14
SQL Data Binding
15
SqlDataSource and Caching Support declarative caching 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
16
<asp:SqlDataSourceID="Countries"RunAt="server" SelectCommand="select..." EnableCaching="true" CacheDuration="60" /> <asp:DropDownListID="MyDropDownList"DataSourceID="Countries“DataTextField="country"AutoPostBack="true" RunAt="server" /> Caching Query Results
17
Parameterized Commands Parameter properties Parameterized database commands 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
18
Parameters 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
19
Parameter 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 ProfileParameterBinds a replaceable parameter to a profile property QueryStringParameterBinds a replaceable parameter to a query string parameter ParameterBinds a replaceable parameter to a data field SessionParameterBinds a replaceable parameter to a session variable
20
Using ControlParameter <asp:SqlDataSource ID="Countries" RunAt="server" SelectCommand="select distinct..." /> <asp:SqlDataSource ID="Customers" RunAt="server" SelectCommand="select * from customers where country=@Country"> <SelectParameters> <asp:ControlParameter Name="Country" <asp:ControlParameter Name="Country"ControlID="MyDropDownList" PropertyName="SelectedValue" /> </SelectParameters></asp:SqlDataSource><asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> DataTextField="country" AutoPostBack="true" RunAt="server" />
21
Calling Stored Procedures <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCountries" /> SelectCommand="proc_GetCountries" /> <asp:SqlDataSource ID="Customers" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCustomers"> SelectCommand="proc_GetCustomers"> <asp:ControlParameter Name="Country" ControlID="MyDropDownList" <asp:ControlParameter Name="Country" ControlID="MyDropDownList" PropertyName="SelectedValue" /> PropertyName="SelectedValue" /> </asp:SqlDataSource> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> DataTextField="country" AutoPostBack="true" RunAt="server" /> CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers SELECT * FROM Customers WHERE Country = @Country WHERE Country = @CountryGO CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers SELECT * FROM Customers WHERE Country = @Country WHERE Country = @CountryGO CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country SELECT DISTINCT Country FROM Customers FROM Customers ORDER BY Country ORDER BY CountryGO CREATE PROCEDURE proc_GetCountries AS SELECT DISTINCT Country SELECT DISTINCT Country FROM Customers FROM Customers ORDER BY Country ORDER BY CountryGO
22
SqlDataSource
23
Data Source Capabilities Common data operations get easier Sorting and paging Selecting, updating, inserting, deleting Page developer Sets properties to enable operations Ex., UpdateCommand “Smart” data-bound controls Use these capabilities directly Ex.,, Ex.,,
24
Sorting, Paging, Updating
25
Data Source Paging Previous demo does paging in UI layer SqlDataSource returns all data rows Performs paging by rendering subset of rows Paging supported on data source interface Select (int startRowIndex, int maxRows) Requires user-defined procedure or custom code Data-bound controls Don’t need to page in the UI layer Useful (and required) for large amounts of data
26
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 Data source applies parameters to command Relies on naming convention for parameters Keys, OldValues formatted with “original_” prefix OldValuesParameterFormatString defines prefix
27
Programmability Data source events Enable custom processing Use event to: Manipulate command and parameters Cancel operations Handle errors Retrieve return values and output params Rows affected Data-bound controls expose similar events
28
Data Source Events Sub MySource_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs) Dim cmd As System.Data.SqlClient.SqlCommand = e.Command Dim cmd As System.Data.SqlClient.SqlCommand = e.Command cmd.Parameters(“UserId”).Value = User.Identity.Name cmd.Parameters(“UserId”).Value = User.Identity.Name End Sub Page.aspx.vb Page.aspx
29
ObjectDataSource Most applications encapsulate data logic Best practice and simplifies maintenance Embedding SQL code is not recommended ObjectDataSource Bind to custom business objects Visual Studio data components Parallels SqlDataSource in object model
30
Web Page DataSourceID = ObjectDataSource1 ObjectDataSourceObjectDataSource NorthwindDatabase OrdersComponent OrderItemsComponent CompaniesComponent <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrders UpdateMethod = UpdateOrder DeleteMethod = DeleteOrder Returns IEnumerable of Orders Order.OrderID Order.OrderID Order.OrderName Order.OrderName Order.OrderDate Order.OrderDate
31
ObjectDataSource Select method can return any Object IEnumerable list Collection or array GetProducts() -> ProductCollection GetProductsDataSet() -> DataSet GetProduct (int productId) -> Product
32
ObjectDataSource Update, Insert, Delete methods Take individual fields or data item object For automatic updates/inserts/deletes Property or parameter names must match selected fields for GridView/DetailsView UpdateProduct (int id, String name, double price) UpdateProduct (Product p) // p.Name, p.Price, etc. DeleteProduct (int id)
33
Key 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
34
Key Properties (cont’d) 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
35
Initialization and Clean-Up Data operation methods Can identify static methods Can identify instance methods If instance methods are used: New class instance on each call Must have public default constructor ObjectCreated and ObjectDisposing Events to initialize or clean-up
36
Using ObjectDataSource
37
What about DataSets? Works for both Web and client applications Created from DB schema Dynamic SQL Stored Procedures Exposes methods to “Fill” and “Fetch” Auto-generated Insert/Update/Delete “A middle tier data access layer for Web and client”
38
What about DataSets? Supports partial classes for custom logic Built in support for common tasks Select, Update, Insert, Delete Batch updates, Conflict resolution* Works with Web services and remoting DataTable can be standalone (XmlSerializable, ReadXml) Exposes “GetBy” for stateless calls Can be used with custom base classes
39
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 CheckBoxFields Declared in element Highly customizable UI
40
GridView Example <asp:SqlDataSourceID="Employees"RunAt="server" SelectCommand="select lastname,.../> <asp:GridViewDataSourceID="Employees"Width="100%" RunAt="server" />
41
Rendered GridView
42
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 from URL text
43
Specifying Field Types <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="select photo, lastname, firstname, title from employees" /> SelectCommand="select photo, lastname, firstname, title from employees" /> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" AutoGenerateColumns="false" > AutoGenerateColumns="false" > </asp:GridView>
44
Rendered Output
45
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
46
DetailsView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="select employeeid, photo,... from employees" /> SelectCommand="select employeeid, photo,... from employees" /> <asp:DetailsView DataSourceID="Employees" RunAt="server" AllowPaging="true" AutoGenerateRows="false" AllowPaging="true" AutoGenerateRows="false" PagerSettings-Mode="NextPreviousFirstLast"> PagerSettings-Mode="NextPreviousFirstLast"> </asp:DetailsView>
47
Rendered Output
48
Master-Detail
49
SQL Cache Invalidation 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
50
Using SqlCacheDependency with the Application Cache Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products"); new SqlCacheDependency ("Northwind", "Products"); Database name Table name
51
Using SqlCacheDependency with the Output Cache <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> SqlDependency="Northwind:Products" %> Database name Table name
52
Using SqlCacheDependency with SqlDataSource <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost;database=northwind;..." ConnectionString="server=localhost;database=northwind;..." SelectCommand="select distinct country from customers order by country" SelectCommand="select distinct country from customers order by country" EnableCaching="true" CacheDuration="60000" EnableCaching="true" CacheDuration="60000" SqlCacheDependency="Northwind:Customers" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> DataTextField="country" AutoPostBack="true" RunAt="server" /> Database name Table name
53
Cache Configuration <cache> 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 <sqlCacheDependency>
54
SQL Cache Invalidation
55
Review Simplified data binding Data source controls Data controls GridView and DetailsView controls Editing with GridView and DetailsView Caching SQL Cache Invalidation Cache configuration
56
Your Feedback is Important! Please Fill Out a Survey for This Session on CommNet
57
© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.