2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0

Download 2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0

Post on 10-May-2015

169 views

Category:

Software

2 download

Embed Size (px)

TRANSCRIPT

<ul><li>1.Copyright 2005 newtelligence AG. All rights reserved Daniel Fisher Software Engineer, newtelligence AG danielf@newtelligence.com 1st Class Data-Driven Applications with ASP.NET 2.0 Chaostage, Deggenbdorf </li></ul><p>2. 2005 newtelligence Aktiengesellschaft. All rights reserved Who I am Software Engineer, newtelligence AG Developer Consultant Trainer Author for Developer Magazines Expert &amp; Editor for CodeZone.de IIS, ADO.NET Leader of INETA UG VfL-NiederRhein CLIP Member 3. 2005 newtelligence Aktiengesellschaft. All rights reserved Agenda Simplified data binding Data source controls Data controls Xml support Caching Connection string builder Secure connection strings Provider factories Performance tips Connection pooling Asyncronous data access DataSet vs. DataReader 4. 2005 newtelligence Aktiengesellschaft. All rights reserved Simplified Data Binding Data binding expressions are now simpler and support hierarchical (XML) data binding 5. 2005 newtelligence Aktiengesellschaft. All rights reserved DataSource Controls Name Description SqlDataSource Connects data-binding controls to SQL DB AccessDataSource Connects data-binding controls to Access XmlDataSource Connects data-binding controls to XML data ObjectDataSource Connects binding controls to components SiteMapDataSource Connects site navigation controls to data Declarative (no-code) data binding 6. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 7. 2005 newtelligence Aktiengesellschaft. All rights reserved Using SqlDataSource p:SqlDataSource ="SqlDataSource1" nat="server" lectCommand="SELECT [Id], [Name], [Email] FROM [Customer]" nnectionString="" p:GridView ID="GridView1" runat="server" lowPaging="True" lowSorting="True" toGenerateColumns="False" taKeyNames="Id" taSourceID="SqlDataSource1" ... sp:GridView&gt; 8. 2005 newtelligence Aktiengesellschaft. All rights reserved Key SqlDataSource Properties Name Description ConnectionString Connection string used to connect to data source SelectCommand Command used to perform queries InsertCommand Command used to perform inserts UpdateCommand Command used to perform updates DeleteCommand Command used to perform deletes DataSourceMode Specifies whether DataSet or DataReader is used (default = DataSet) ProviderName Specifies provider (default = SQL Server .NET) 9. 2005 newtelligence Aktiengesellschaft. All rights reserved 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/absolute CacheKeyDependency Creates dependency on specified cache key SqlCacheDependency Creates dependency on specified database entity 10. 2005 newtelligence Aktiengesellschaft. All rights reserved ... Caching Results 11. 2005 newtelligence Aktiengesellschaft. All rights reserved Parameterized Commands Parameters 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 Parameter types specify source of parameter values 12. 2005 newtelligence Aktiengesellschaft. All rights reserved Parameters Properties Name Description SelectParameters Specifies parameters for SelectCommand InsertParameters UpdateParameters DeleteParameters FilterParameters Specifies parameters for FilterExpression Specifies parameters for InsertCommand Specifies parameters for UpdateCommand Specifies parameters for DeleteCommand Parameters are added declarative as Tags 13. 2005 newtelligence Aktiengesellschaft. All rights reserved Parameter Types Name Description 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 SessionParameter Binds a replaceable parameter to a session variable Parameter Binds a replaceable parameter to a data field Parameters can have different sources 14. 2005 newtelligence Aktiengesellschaft. All rights reserved Using ControlParameter PolandGermany ...... 15. 2005 newtelligence Aktiengesellschaft. All rights reserved Calling Stored Procedures CREATE PROCEDURE proc_GetCustomers @Country nvarchar (32) AS SELECT * FROM Customers WHERE Country = @Country GO 16. 2005 newtelligence Aktiengesellschaft. All rights reserved Using the SqlDataSource 17. 2005 newtelligence Aktiengesellschaft. All rights reserved XmlDataSource Declarative data binding to XML data Supports caching and XSLT One-way data binding only no updating :-( 18. 2005 newtelligence Aktiengesellschaft. All rights reserved Key XmlDataSource Properties Name Description DataFile Path to file containing XML data TransformFile Path to file containing XSL style sheet EnableCaching XPath XPath expression used to filter data CacheDuration Length of time in seconds data should be cached CacheExpirationPolicy Specifies whether cache duration is sliding or absolute CacheKeyDependency Creates dependency on specified cache key Specifies whether caching is enabled (default = false) 19. 2005 newtelligence Aktiengesellschaft. All rights reserved XmlDataSource ... ... ... 20. 2005 newtelligence Aktiengesellschaft. All rights reserved Using the XmlDataSource 21. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 22. 2005 newtelligence Aktiengesellschaft. All rights reserved Key ObjectDataSource Properties Name Description TypeName Type name of data component SelectMethod Method called on data component to perform queries InsertMethod UpdateMethod DeleteMethod EnableCaching Specifies 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 23. 2005 newtelligence Aktiengesellschaft. All rights reserved Key ObjectDataSource Properties II Name Description InsertParameters Specifies parameters for InsertMethod UpdateParameters Specifies parameters for UpdateMethod DeleteParameters Specifies parameters for DeleteMethod SelectParameters Specifies parameters for SelectMethod CacheDuration Length of time in seconds data should be cached SqlCacheDependency Creates dependency on specified database entity 24. 2005 newtelligence Aktiengesellschaft. All rights reserved Initialization and Clean-Up SelectMethod et al can identify static methods or instance methods If instance methods are used: New class instance is created 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 25. 2005 newtelligence Aktiengesellschaft. All rights reserved Using the ObjectDataSource 26. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 27. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 HyperLinkField Renders columns of hyperlinks TemplateField Renders columns using HTML templates CommandField Renders controls for selecting and editing GridView data ImageField Renders columns of images 28. 2005 newtelligence Aktiengesellschaft. All rights reserved Specifying Field Types 29. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 30. 2005 newtelligence Aktiengesellschaft. All rights reserved DetailsView Example 31. 2005 newtelligence Aktiengesellschaft. All rights reserved Master-Detail Views 32. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 33. 2005 newtelligence Aktiengesellschaft. All rights reserved Editing with GridViews Edit buttons Primary key Update command Update parameters 34. 2005 newtelligence Aktiengesellschaft. All rights reserved Conflict Detection First-in wins Update fails if data has changed Structure UpdateCommand accordingly ConflictDetection="CompareAllValues Last-in wins Update succeeds even if data has changed Structure UpdateCommand accordingly ConflictDetection="OverwriteChanges" 35. 2005 newtelligence Aktiengesellschaft. All rights reserved Optimistic Concurrency Updates ... 36. 2005 newtelligence Aktiengesellschaft. All rights reserved Last-In-Wins Updates ... 37. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 38. 2005 newtelligence Aktiengesellschaft. All rights reserved Handling Update Errors ... ... 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 } } 39. 2005 newtelligence Aktiengesellschaft. All rights reserved Editing with GridView and DetailsView 40. 2005 newtelligence Aktiengesellschaft. All rights reserved XML Support ADO.NET Native XML Data Type DataTable, DataSet, DataReader SQL Server 2005 as an XML store Durable, recoverable, consistent Mature management tools Integration with existing relational data SQL Server 2005 as an XML source Accessible over HTTP and SOAP Exposes all data as XML Can be programmed just like a web service 41. 2005 newtelligence Aktiengesellschaft. All rights reserved XML data type Native SQL type Well-formed and validation checks Optional XML Schema enforcement Behaviours allow XQuery and extensions Exist, Query, Modify, Value Native XML Store XML Data Type 42. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 43. 2005 newtelligence Aktiengesellschaft. All rights reserved aspnet_regsql.exe -S localhost -E -d Northwind -ed Preparing a Database Use Aspnet_regsql.exe or SqlCache- DependencyAdmin to prepare database* Trusted connection Database name Enable database * Not necessary for SQL Server 2005 Server name 44. 2005 newtelligence Aktiengesellschaft. All rights reserved aspnet_regsql -S localhost -E -d Northwind t Products -ed Preparing a Table Use Aspnet_regsql.exe or SqlCache- DependencyAdmin to prepare table* Trusted connection Database name Table name Server name Enable table * Not necessary for SQL Server 2005 45. 2005 newtelligence Aktiengesellschaft. All rights reserved Preparing Web.config 46. 2005 newtelligence Aktiengesellschaft. All rights reserved Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products"); Using SqlCacheDependency with the Application Cache Database name Table name 47. 2005 newtelligence Aktiengesellschaft. All rights reserved Using SqlCacheDependency with the Output Cache Database name Table name 48. 2005 newtelligence Aktiengesellschaft. All rights reserved Using SqlCacheDependency with SqlDataSource Database name Table name 49. 2005 newtelligence Aktiengesellschaft. All rights reserved 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 50. 2005 newtelligence Aktiengesellschaft. All rights reserved SqlDependency Bind a SqlDependency to Command Specify the Callback Handler Add Callback Handler SqlDependency _dep = new SqlDependency(cmd); _dep.OnChange += new OnChangeEventHandler(DataChanged); static void DataChange(Object sender, SqlNotificationEventArgs args) { } 51. 2005 newtelligence Aktiengesellschaft. All rights reserved SQL Cache Dependencies 52. 2005 newtelligence Aktiengesellschaft. All rights reserved ConnectionStringBuilder Build Connection Strings programmatically Fetch information or edit them? SqlConnectionStringBuilder _connbuilder = new SqlConnectionStringBuilder(); _connbuilder.DataSource = "localhost"; _connbuilder.UserID = "sa"; _connbuilder.Password = "$3cUr3"; SqlConnection _conn = new SqlConnection(_connbuilder.ConnectionString); 53. 2005 newtelligence Aktiengesellschaft. All rights reserved Securing Connection Strings AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA4rwj++4ocEqW to+xX+GfmQQAAAACAAAAAAADZgAAqAAAABAAAAAAenfLPcbvaitCjiKB/JM+AAAAAASAAACgAAAAEAAAAKC muCXyu0Mor8UIouCX/6xwAQAAzyodkmx05YVrgZF3Jp/6KrcpBfw3k6D1vNi8DE/neOsXwfZ2Terw0eSgHl aFX/q4Q+uoBy2imBlO9z+tGBmS1SDDietOgLFVPBd0M/AHUoBnNihFjh2RocoBuZltF3+albLYAnDwbE6QZ 0/Pdm9VKB24Wv1OMZSL9Re+rQOlpuCfN2Y0T97h5xVlH4qMHlquCvehiZcjqaG8ZqdLh5gQd8uZHClyG7Dc 70/4bzaE/cI+CLzKtUtLOcWj8cpQ3Y9xnKB7GdyxE9L9...</p>