TechEd 2005

1/24/2011 8:20 AM

WEB325 Building Data-Driven Web Sites in DataASP.NET 2.0

Rob Howard rhoward@telligent.com Telligent Corporation

Contact and Slides
Rob Howard
rhoward@telligent.com www.telligent.com

Review: ASP.NET 1.X
ASP.NET 1.X
Introduced data controls Introduced data binding concepts

Telligent
.NET Software Development Company Builds Community Server (communityserver.org)

Working with data in ASP.NET 1.X
Easy and simple Too much code still required though

Download Slides & Demos
www.robwww.rob-howard.net Will be posted ASAP

ASP.NET 2.0
Specifically addresses common scenarios Makes working with data even easier

Agenda
Safer connection string storage Data binding gets easier Declarative data binding Working with the new data controls Caching data

Connection String Storage
Persistence and declarative referencing
Stored in *.config Avoid hard-coding within pages/code hardCan be optionally encrypted

BuiltBuilt-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

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

1

NET 2.ASP.XML data binding --> --> <%# XPath ("Price") %> ObjectDataSource SiteMapDataSource SqlDataSource Data binding to SQL Database Microsoft SQL Server. Oracle. and DeleteCommand Optional caching of query results Parameterized operation © 2005 Microsoft Corporation. Using SqlDataSource <asp:SqlDataSource ID="Titles" ConnectionString="<%$ connectionStrings:pubs %>" RunAt="server³ SelectCommand="select title_id. etc.NET 1. in this summary. Microsoft makes no warranties.Eval (Container.config: <connectionStrings> <add name="pubs³ ProviderName=³«´ connectionString=³«´ /> </connectionStrings> Connection Strings Page.ConnectionStrings(³pubs´) Data Binding Gets Easier Expressions are cleaner Support hierarchical (XML) data binding <!-<!-. This presentation is for informational purposes only. DB . UpdateCommand.Equivalent ASP.x data binding expression --> --> <%# DataBinder.0 data binding expression --> --> <%# Eval ("Price") %> AccessDataSource XmlDataSource <!-<!-. express or implied. "Price") %> Declarative Data Binding Controls bound at appropriate time WireWire-up done through properties Page lifecycle knowledge not required Name SqlDataSource Description Connects data-binding controls to SQL databases Connects data-binding controls to Access databases Connects data-binding controls to XML data Connects data-binding controls to data components Connects site navigation controls to site map data <!-<!-. price from titles" /> wowo-way data binding supported SelectCommand InsertCommand.   <asp:DataGrid DataSourceID="Titles" RunAt="server" /> 2 .DataItem.TechEd 2005 1/24/2011 8:20 AM Config Connection Strings Web.aspx: <asp:SqlDataSource Id=³MySource´ ConnectionString=³<%$ connectionStrings:pubs %>´ SelectCommand=³select au_id from authors´ runat=³server´/> Code.vb: Dim connstr As String = ConfigurationSettings. All rights reserved. title.

. ¡ ¥ ¥ Caching Query Results <asp:SqlDataSource ID="Countries" RunAt="server" Description Specifies whether caching is enabled (default = false) Length of time in seconds results should be cached Specifies whether cache duration is sliding or absolute Creates dependency on specified cache key Creates dependency on specified database entity SelectCommand="select ." EnableCaching="true" CacheDuration="60" /> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries³ DataTextField="country" AutoPostBack="true" RunAt="server" /> Parameters Pro erties Name electParameters   escri tion  am le: et alue for R clause in electCommand from uery string arameter or item selected in dro -do n list ¢ § ¨ ©       ecifies arameters for electCommand   ¦ ¦ InsertParameters dateParameters eleteParameters ecifies arameters for InsertCommand ecifies arameters for dateCommand  !  !  am le: et alue for from ridVie § ¨ § ¢  ecifies arameters for eleteCommand " R clause in  eleteCommand FilterParameters "   ecifies arameters for Filter ression # $ ©     3 . Microsoft makes no warranties.NET provider) SQL Data Binding DeleteCommand DataSourceMode ProviderName SqlDataSource and Caching Support declarative caching Name EnableCaching CacheDuration CacheExpirationPolicy CacheKeyDependency SqlCacheDependency Parameteri ed Commands Parameter ro erties Parameteri ed data ase commands £ ¤¤ ¢ ¢ © 2005 Microsoft Corporation.. express or implied. in this summary.TechEd 2005 1/24/2011 8:20 AM SqlDataSource Properties Name ConnectionString SelectCommand InsertCommand pdateCommand Description Connection string used to connect to data source Command used to perform queries Command used to perform inserts Command used to perform updates Command used to perform deletes Specifies whether DataSet or DataReader is used (default = DataSet) Specifies provider (default = SQL Server . All rights reserved. This presentation is for informational purposes only.

." SelectCommand="proc_GetCustomers"> 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" /> SqlDataSource 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 Data Source Capabilities Co o % % & % & ata operatio s et easier ' % & & Sorti a pa i Selecti . up ati . Up ati ³S art´ ata-bou ata1 ( ) 3 ' 4 Use t ese capabilities irectl . i serti % % . ( ) ' 0 co trols 4 . Up ateCo a ' % & % & % & Sorti 0 % ' . This presentation is for informational purposes only.TechEd 2005 1/24/2011 8:20 AM Parameter Types Name Parameter ControlParameter CookieParameter FormParameter ProfileParameter QueryStringParameter SessionParameter sing ControlParameter <asp:SqlDataSource ID="Countries" RunAt="server" Description Binds a replaceable parameter to a data field Binds a replaceable parameter to a control property Binds a replaceable parameter to a cookie value Binds a replaceable parameter to a form field Binds a replaceable parameter to a profile property Binds a replaceable parameter to a query string parameter Binds a replaceable parameter to a session variable SelectCommand="select distinct . Microsoft makes no warranties. express or implied......" /> <asp:SqlDataSource ID="Customers" RunAt="server" 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. a i ..database=northwind.. in this summary... <asp:DetailsVie > ' 2 4 © 2005 Microsoft Corporation." SelectCommand="proc_GetCountries" SelectCommand="proc_GetCountries" /> <asp:SqlDataSource ID="Customers" RunAt="server" ConnectionString="server=localhost. eleti ' % a e e eloper Sets properties to e able operatio s .database=northwind. <asp: ri Vie >. All rights reserved.

Old alues Delete: Keys.SqlCommand = e. Old alues formatted with original_ prefix Old aluesParameterFormatString defines prefix 9 @ 8 8 66 8 8 8 DataData-bound controls Don¶t need to page in the I layer seful (and required) for large amounts of data 6 6 Programmability Data source events Enable custom processing Data Source Events Page.Name End Sub se event to: Manipulate command and parameters Cancel operations Handle errors Retrieve return values and output params Rows affected DataData-bound controls expose similar events ObjectDataSource o ta B G H S R <asp:ObjectDataSource ID=³MySource´ TypeName=³CustomersDB´ SelectMethod=³GetCustomersByRegion´ UpdateMethod=³UpdateCustomer´ runat=³server´/> © 2005 Microsoft Corporation. in this summary.aspx.SqlClient. int maxRows) Requires user-defined procedure or custom code user- Dictionaries passed to data source operation pdate: Keys.aspx <asp:SqlDataSource ID=³MySource´ « OnSelecting=³MySource_Selecting´ SelectCommand=³sp_GetUserPreferences´ runat=³server´/> ObjectDataSource Web Page licatio P Q P U V e ca DD H R I Q H ulate ata lo ic E F H R P P P R R P Q Q D B B e t ractice a i lifie ai te a ce be i S co e i ot reco e e Q I Q P T ObjectDataSource i to cu to bu i e object Vi ual Stu io ata co o e t arallel S lDataSource i object G W P Q H R H P H H H H Q Q R P P H I H P X C C C DataSourceID = ObjectDataSource1 Returns IEnumerable of Orders Order. This presentation is for informational purposes only. Microsoft makes no warranties. alues. All rights reserved.OrderName Order.Command cmd.Parameters(³UserId´). Old alues Data source applies parameters to command Relies on naming convention for parameters Keys.OrderDate <asp:ObjectDataSource ID = ObjectDataSource1 TypeName = OrdersComponent SelectMethod = GetOrders UpdateMethod = UpdateOrder DeleteMethod = DeleteOrder o el Q R OrderItemsComponent OrdersComponent Northwind Database CompaniesComponent 5 . Deletes Grid iew Extracts values from input controls Keys from viewstate (DataKeyNames) 7 SqlDataSource returns all data rows Performs paging by rendering subset of rows Paging supported on data source interface Select (int startRowIndex.vb Sub MySource_Selecting(ByVal sender As Object. 5 A Page.OrderID Order. Inserts.Value = User. ByVal e As SqlDataSourceCommandEventArgs) Dim cmd As System.Identity. express or implied.Data.TechEd 2005 1/24/2011 8:20 AM Data Source Paging Previous demo does paging in I layer 5 pdates.

Delete methods Take individual fields or data item object pdateProduct (int id Strin na e c dou le price) d DeleteProduct (int id) For automatic updates/inserts/deletes Property or parameter names must match selected fields for Grid iew/Details iew Y Y ` ` pdateProduct (Product p) a b a p a e p Price etc c f a a e e f g f Key Properties Name TypeName SelectMethod InsertMethod pdateMethod Key Properties (cont¶d) Description Name CacheDuration SqlCacheDependency SelectParameters InsertParameters pdateParameters Description Length of time in seconds data should be cached Creates dependency on specified database entity Specifies parameters for SelectMethod Specifies parameters for InsertMethod Specifies parameters for pdateMethod h Type name of data component Method called on data component to perform queries Method called on data component to perform inserts Method called on data component to perform updates Method called on data component to perform deletes Specifies whether caching is enabled (default = false) DeleteMethod EnableCaching Initiali ation and Clean. Microsoft makes no warranties.TechEd 2005 1/24/2011 8:20 AM ObjectDataSource Select method can return any Object IEnumerable list Collection or array GetProducts() -> ProductCollection GetProductsDataSet() -> DataSet GetProduct (int productId) -> Product ObjectDataSource pdate. Insert.p CleanData operation methods Can identify static methods Can identify instance methods © 2005 Microsoft Corporation. This presentation is for informational purposes only. All rights reserved. express or implied. in this summary. h DeleteParameters h Specifies parameters for DeleteMethod If instance methods are used: New class instance on each call Must have public default constructor sing ObjectDataSource ObjectCreated and ObjectDisposing Events to initiali e or clean-up cleani 6 .

Conflict resolution* … Wor s for both Web a d clie t a reated fro u v x v w p q q s ‚ licatio s q r r D sche a D a ic S Stored rocedures y € E oses ethods to ³ ill´ a d ³ etch´ AutoAuto. in this summary. pdate. Microsoft makes no warranties. updating. . All rights reserved. This presentation is for informational purposes only.. Delete Batch updates. or link) Renders Booleans as check boxes Renders controls for selecting and editing Grid iew data ‘ Renders columns of hyperlinks Renders columns of images from RL text Renders columns using HTML templates ’ 7 . and deleting support Supports rich assortment of field types.. selecting.TechEd 2005 1/24/2011 8:20 AM What about DataSets? ³A middle tier data access layer for Web and client´ What about DataSets? Supports partial classes for custom logic Built in support for common tasks Select. paging.e erated I sert/U date/Delete t ƒ q ƒ r q q „ r Works with Web services and remoting DataTable can be standalone (XmlSeriali able./> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" /> ‰  Grid iew Field Types Name BoundField ButtonField CheckBoxField CommandField HyperLinkField ImageField TemplateField Description Renders columns of text from fields in data source Renders columns of buttons (push button. image. Insert. including CheckBoxFields Declared in Columns element Highly customi able I Rendered Grid iew © 2005 Microsoft Corporation. ReadXml) Exposes GetBy for stateless calls Can be used with custom base classes † ‡ ˆ t Grid iew Control Enhanced DataGrid control Renders sets of records as HTML tables BuiltBuilt-in sorting.  Grid iew Example <asp:SqlDataSource ID="Employees" RunAt="server" SelectCommand="select lastname. express or implied.

database=northwind... title from employees" /> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" AutoGenerateColumns="false" > <Columns> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <%# Eval ("firstname") + " " + Eval ("lastname") %> </ItemTemplate> </asp:TemplateField> <asp:BoundField HeaderText="Title" DataField="title" /> </Columns> </asp:GridView> Rendered Output Details iew Control Renders individual records Pair with Grid iew for master-detail views masterOr use without Grid iew to display individual records “ ““ Details iew Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost... lastname.. in this summary. express or implied." SelectCommand="select photo. This presentation is for informational purposes only. deleting ses same field types as Grid iew Declared in Fields element Highly customi able I Rendered Output © 2005 Microsoft Corporation. inserting. firstname." SelectCommand="select employeeid. from employees" /> <asp:DetailsView DataSourceID="Employees" RunAt="server" AllowPaging="true" AutoGenerateRows="false" PagerSettingsPagerSettings-Mode="NextPreviousFirstLast"> <Fields> <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> BuiltBuilt-in paging. . All rights reserved..database=northwind.. ” • MasterMaster-Detail 8 . updating. photo.TechEd 2005 1/24/2011 8:20 AM Specifying Field Types <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost.. Microsoft makes no warranties.

products. 9 . Links cached items to database entities Compatible with SQL Server 7. "Products"). 2000. new SqlCacheDependency ("Northwind"..TechEd 2005 1/24/2011 8:20 AM SQL Cache Invalidation New cache dependency type Embodied in SqlCacheDependency class Configured through sqlCacheDependency configuration section ASP. This presentation is for informational purposes only." 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 ore QL Cache Invali ation ˜ j d g < lCache e en enc > © 2005 Microsoft Corporation.a e er i tence et a i u ize er a an ore ™ d e ™ f ™ d e ™ d e i ™ e d e e f g h g g e d g f f f ˜ ˜ – Database name Table name Using SqlCacheDependency with SqlDataSource <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="server=localhost.NET output cache — sing SqlCacheDependency with the Application Cache Cache.. <out utCache etting > na le/ i a le out ut caching na le/ i a le i . Microsoft makes no warranties. All rights reserved.. express or implied. in this summary.database=northwind. 2005 Using SqlCacheDependency with the Output Cache <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> Database name Table name Cache Configuration <cache> na le/ i a le a lication cache na le/ i a le ite e iration an ™ d e ™ f f ™ d e ™ g h f ˜ <out utCache>.Insert ("Products".NET application cache ASP.

express or implied. 10 . Mic rosoft makes no warranties. © 2005 Microsoft Corporation. This presentation is for informational purposes only. This presentation is for informational purposes only. in this summary. in this summary.TechEd 2005 1/24/2011 8:20 AM Review Simplified data binding Data source controls Data controls Grid iew and Details iew controls Editing with Grid iew and Details iew k k k k Your Feedback is Important! Please Fill Out a Survey for This Session on CommNet Caching SQL Cache Invalidation Cache configuration © 2005 Microsoft Corporation. All rights reserved. Microsoft makes no warranties. All rights reserved. express or implied.

Sign up to vote on this title
UsefulNot useful