Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

486 views

Published on

Published in: Software
  • Be the first to comment

  • Be the first to like this

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

  1. 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
  2. 2. © 2005 newtelligence Aktiengesellschaft. All rights reserved Who I am  Software Engineer, newtelligence AG •Developer •Consultant •Trainer  Author for Developer Magazines  Expert & Editor for CodeZone.de •IIS, ADO.NET …  Leader of INETA UG VfL-NiederRhein •CLIP Member
  3. 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. 4. © 2005 newtelligence Aktiengesellschaft. All rights reserved 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 --> <%# Eval ("Price") %> <!-- XML data binding --> <%# XPath ("Price") %>
  5. 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. 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. 7. © 2005 newtelligence Aktiengesellschaft. All rights reserved Using SqlDataSource p:SqlDataSource ="SqlDataSource1" nat="server" lectCommand="SELECT [Id], [Name], [Email] FROM [Customer]" nnectionString="<%$ ConnectionStrings:ConnectionString %>" p:GridView ID="GridView1" runat="server" lowPaging="True" lowSorting="True" toGenerateColumns="False" taKeyNames="Id" taSourceID="SqlDataSource1" <Columns> <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" /> ... </Columns> sp:GridView>
  8. 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. 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. 10. © 2005 newtelligence Aktiengesellschaft. All rights reserved <asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [Name] FROM [Customer]" ConnectionString="<%$ ConnectionStrings:ConnectionString %>„ EnableCaching="true" CacheDuration="60" /> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" /> ... </Columns> </asp:GridView> Caching Results
  11. 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. 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. 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. 14. © 2005 newtelligence Aktiengesellschaft. All rights reserved Using ControlParameter <asp:DropDownlist AutoPostBack="true" runat="server" ID=„CountryDropDown" > <asp:ListItem>Poland</asp:ListItem> <asp:ListItem>Germany</asp:ListItem> </asp:DropDownlist> <asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [Id], [Name], [Email] FROM [Customer] WHERE Country=@Country" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" EnableCaching="true" CacheDuration="60" > <SelectParameters> <asp:ControlParameter ControlID="CountryDropDown" Name="Country" /> </SelectParameters> </asp:SqlDataSource> ......
  15. 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 <asp:SqlDataSource ID="Customers" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="proc_GetCustomers"> <SelectParameters> <asp:ControlParameter Name="Country" ControlID="MyDropDownList“ /> </SelectParameters> </asp:SqlDataSource> <asp:DropDownList ID="MyDropDownList" DataSourceID="Countries" DataTextField="country" AutoPostBack="true" RunAt="server" /> <asp:DataGrid DataSourceID="Customers" RunAt="server" />
  16. 16. © 2005 newtelligence Aktiengesellschaft. All rights reserved Using the SqlDataSource
  17. 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. 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. 19. © 2005 newtelligence Aktiengesellschaft. All rights reserved XmlDataSource <Customers> <Customer Id="1" Name="Daniel Fisher" Email="DanielF@newtelligence.com" Location="Poland" /> <Customer Id="2" Name="Clemens Vasters" Email="ClemensV@newtelligence.com" Location="Poland" /> ... </Customers> ... <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/App_Data/Data.xml" /> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="XmlDataSource1" DataTextField="Name" DataValueField="Id" > </asp:DropDownList> ...
  20. 20. © 2005 newtelligence Aktiengesellschaft. All rights reserved Using the XmlDataSource
  21. 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. 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. 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. 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. 25. © 2005 newtelligence Aktiengesellschaft. All rights reserved Using the ObjectDataSource
  26. 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 <Columns> element  Highly customizable UI
  27. 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. 28. © 2005 newtelligence Aktiengesellschaft. All rights reserved Specifying Field Types <asp:GridView DataSourceID=“DataSource1" 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>
  29. 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 <Fields> element  Highly customizable UI
  30. 30. © 2005 newtelligence Aktiengesellschaft. All rights reserved DetailsView Example <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="server=localhost;database=northwind;..." SelectCommand="select employeeid, photo, ... from ..." /> <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>
  31. 31. © 2005 newtelligence Aktiengesellschaft. All rights reserved Master-Detail Views
  32. 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. 33. © 2005 newtelligence Aktiengesellschaft. All rights reserved <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString=“..." 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" /> Editing with GridViews Edit buttons Primary key Update command Update parameters
  34. 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. 35. © 2005 newtelligence Aktiengesellschaft. All rights reserved Optimistic Concurrency Updates <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="..." SelectCommand=“..." UpdateCommand=“..." ConflictDetection=“CompareAllValues"> <UpdateParameters> ... </UpdateParameters> </asp:SqlDataSource> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server“ DataKeyNames="EmployeeID" AutoGenerateEditButton="true" />
  36. 36. © 2005 newtelligence Aktiengesellschaft. All rights reserved Last-In-Wins Updates <asp:SqlDataSource ID="Employees" RunAt="server" ConnectionString="..." SelectCommand=“..." UpdateCommand=“..." ConflictDetection="OverwriteChanges"> <UpdateParameters> ... </UpdateParameters> </asp:SqlDataSource> <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server“ DataKeyNames="EmployeeID" AutoGenerateEditButton="true" />
  37. 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. 38. © 2005 newtelligence Aktiengesellschaft. All rights reserved Handling Update Errors <asp:SqlDataSource ID="Employees" RunAt="server" ... UpdateCommand="..." OnUpdated="OnUpdateComplete"> ... </asp:SqlDataSource> ... 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. 39. © 2005 newtelligence Aktiengesellschaft. All rights reserved Editing with GridView and DetailsView
  40. 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. 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. 42. © 2005 newtelligence Aktiengesellschaft. All rights reserved 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
  43. 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. 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. 45. © 2005 newtelligence Aktiengesellschaft. All rights reserved Preparing Web.config <configuration> <connectionStrings> <add name="Northwind" connectionString="..." /> </connectionStrings> <system.web> <caching> <sqlCacheDependency enabled="true" pollTime="5000"> <databases> <add name="Northwind" connectionStringName="Northwind" /> </databases> </sqlCacheDependency> </caching> <system.web> </configuration>
  46. 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. 47. © 2005 newtelligence Aktiengesellschaft. All rights reserved <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> Using SqlCacheDependency with the Output Cache Database name Table name
  48. 48. © 2005 newtelligence Aktiengesellschaft. All rights reserved <asp:SqlDataSource ID="Countries" RunAt="server" ConnectionString="..." SelectCommand="select country from customers" EnableCaching="true" CacheDuration="60000" SqlCacheDependency="Northwind:Customers" /> <asp:DropDownList ID="MyDropDownList" Runat="server" DataSourceID="Countries“ DataTextField="country"/> Using SqlCacheDependency with SqlDataSource Database name Table name
  49. 49. © 2005 newtelligence Aktiengesellschaft. All rights reserved Cache Configuration  <cache> •Enable/disable application cache •Enable/disable item expiration and more  <outputCache>, <outputCacheSettings> •Enable/disable output caching •Enable/disable disk-based persistence •Set maximum size per app and more  <sqlCacheDependency>
  50. 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. 51. © 2005 newtelligence Aktiengesellschaft. All rights reserved SQL Cache Dependencies
  52. 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. 53. © 2005 newtelligence Aktiengesellschaft. All rights reserved Securing Connection Strings <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider"> <EncryptedData> <CipherData> <CipherValue>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+CLzKtUtLOcWj8cpQ3Y9xnKB7GdyxE9L94ofyeA99uOLT02sO3OoOjZPyGGd651Xrkqb9eGv x3RfHqwnbKTDMf39AxIsbEu1qebA7tsATM/shc/X5nrukL+6VWBxzgP5JS1PM6jMzOmCtloMRb0Om3bsaoc 4yBPaiKM6p02LwvwB8C2w/VaI501a5iBQ+MX2aOn1uF8b+Gb3zDWWLpqC+6m80Zflza5WuoqYVGrUGPkS0r 1E5b6pGwZnm0XOXRKoUAAAASQxsCa2kp8XwDllVsC2Pq/PjXOU=</CipherValue> </CipherData> </EncryptedData> </connectionStrings> <connectionStrings> <add name="Data" connectionString="Server=Local; Database=Adwentureworks; UID=sa; PWD=$3cUr3" providerName="System.Data.SqlClient" /> </connectionStrings> Configuration _config = WebConfigurationManager.OpenWebConfiguration("~"); ConnectionStringsSection _section = _config.GetSection("connectionStrings") as ConnectionStringsSection; _section.SectionInformation.ProtectSection( "DataProtectionConfigurationProvider");
  54. 54. © 2005 newtelligence Aktiengesellschaft. All rights reserved Securing Connection Strings
  55. 55. © 2005 newtelligence Aktiengesellschaft. All rights reserved Factory Class Hierarchy IDb* interfaces (e.g. IDbConnection) Db* abstract base classes (e.g. DbConnection) Db*Base implementation classes Sql OleDb ODBC Oracle 3rd Party 1 3rd Party 2 Provider- Independent apps code to this layer Provider- specific apps code to this layer
  56. 56. © 2005 newtelligence Aktiengesellschaft. All rights reserved Using a Provider Factory Import the Required Namespace: Create the Factory Instance: Create Required Object Instances: using System.Data.Common static DbProviderFactory factory = DbProviderFactories.GetFactory("provider-name") DbConnection con = factory.CreateConnection() DbCommand cmd = con.CreateCommand()
  57. 57. © 2005 newtelligence Aktiengesellschaft. All rights reserved Connection Pooling  Pooling is enabled by default •Default maximum pool size 100  Pool is configured in connection string  Pool is created for each connection string •Store connection string in a single place  Test for optimal pool sizes •Use SqlServer Profiler or Performance Monitor  Transaction enlistment is transparent SqlConnection c = new SqlConnection( "Server=(local); Integrated Security=SSPI; Database=Customers; Max Pool Size=25; Min Pool Size=3");
  58. 58. © 2005 newtelligence Aktiengesellschaft. All rights reserved Asynchronous Commands Ideal for multiple database queries Usual Beginxxx and Endxxx model Supports Polling, Wait and Callback models Catching asynchronous execution errors Should not generally be used with MARS •use a separate connection for each Command Add "async=true" to connection string
  59. 59. © 2005 newtelligence Aktiengesellschaft. All rights reserved Asynchronous Polling Model Start asynchronous command execution: Wait until execution is complete: Fetch results: IAsyncResult result = MyCommand.BeginExecuteReader() while (! result.IsCompleted) { // execute other code here } SqlDataReader reader = MyCommand.EndExecuteReader(result )
  60. 60. © 2005 newtelligence Aktiengesellschaft. All rights reserved Asynchronous Callback Model Start execution, specifying callback and passing command as the AsyncState: Provide a callback handler: MyCommand.BeginExecuteReader( new AsyncCallback(MyCallback), cmd) void MyCallback(IAsyncResult result) { SqlCommand cmd = (SqlCommand)result.AsyncState; SqlDataReader reader = cmd.EndExecuteReader(result); }
  61. 61. © 2005 newtelligence Aktiengesellschaft. All rights reserved Promotable Transactions  Automatic promotion of local transactions into distributed ones •Uses TransactionContext  Fully integrated with the classes in System.Transactions namespace  Works with transactions started in SQL Server 2005 CLR code •Context flows even if you start in-proc  Don't promote single RM transactions
  62. 62. © 2005 newtelligence Aktiengesellschaft. All rights reserved Auto-promoting a Transaction  Initialize the transaction scope:  Create a connection and do work •Do *not* enrol - uses a local transaction  Create second connection and do work •transaction auto-promoted to distributed  Commit:  Rollback not needed  Dispose of transaction when complete: TransactionScope _scope = new TransactionScope( TransactionScopeOptions.RequiresNew); _scope.Complete = true; _scope.dispose();
  63. 63. © 2005 newtelligence Aktiengesellschaft. All rights reserved DataSet or Not DataSet?  DataSets are huge… •Sometimes too huge  Avoid using the DataSets with often changing data <asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [Id], [Name], [Email] FROM [Customer]" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" DataSourceMode="DataReader" />
  64. 64. © 2005 newtelligence Aktiengesellschaft. All rights reserved Asynchronous Callback Model Start execution, specifying callback and passing command as the AsyncState: Provide a callback handler: MyCommand.BeginExecuteReader( new AsyncCallback(MyCallback), cmd) void MyCallback(IAsyncResult result) { SqlCommand cmd = (SqlCommand) result.AsyncState; SqlDataReader reader = cmd.EndExecuteReader(result); }
  65. 65. © 2005 newtelligence Aktiengesellschaft. All rights reserved When To Use DataSet  Use DataSet populated by a SqlDataAdapter when you want to… •pass disconnected memory-resident cache of data to other components or tiers •use an in-memory relational view •consolidate data from multiple data sources •easily update retrieved data  SqlDataAdapter.Fill opens connection and closes it on return •If the connection is already open, Fill leaves it open
  66. 66. © 2005 newtelligence Aktiengesellschaft. All rights reserved DataSet and Caching  Use DataSets for data caching •Most data is not volatile •Saves roundtrips to the database •Less code than writing custom classes •Keep DataSets around for longer than a Page •Store them in session/global/cache •Expiring Caches are great for DataSets •Growing the Cache as needed with DataSets
  67. 67. © 2005 newtelligence Aktiengesellschaft. All rights reserved Alternatives – DataReader  Use SqlDataReader from SqlCommand.ExecuteReader when: •Dealing with large volumes of data  Too much to maintain in a single cache. •Saving memory is critical •Additional overhead for creating DataSet is too much •Overall performance is critical •Reading rows containing BLOBs cannot be consumed at once  SqlDataReader can pull BLOB data in chunks
  68. 68. © 2005 newtelligence Aktiengesellschaft. All rights reserved Alternatives – DataReader, DataTable There is no need for a DataSet if you just want to work with a DataTable •DataTable.Load(DataReader)  Common DataSet operations now also available on DataTable: •ReadXml, ReadXmlSchema, WriteXml, WriteXmlSchema, Clear, Clone, Copy, Merge, GetChanges
  69. 69. © 2005 newtelligence Aktiengesellschaft. All rights reserved
  70. 70. © 2005 newtelligence Aktiengesellschaft. All rights reserved Thank You  © 2005 newtelligence® Aktiengesellschaft newtelligence® AG Gilleshütte 99 D-41352 Korschenbroich http://www.newtelligence.com info@newtelligence.com  The presentation content is provided for your personal information only. Any commercial or non-commercial use of the presentation in full or of any text or graphics requires a license from newtelligence AG.  This presentation is protected by the German Copyright Act, EU copyright regulations and international treaties.

×