2005 - .net chaostage: 1st class data driven applications with asp.net 2.0

Post on 10-May-2015

175 Views

Category:

Software

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Copyright © 2005 newtelligence® AG. All rights reserved

Daniel FisherSoftware Engineer, newtelligence® AG

danielf@newtelligence.com

1st Class Data-Driven Applications with ASP.NET

2.0

1st Class Data-Driven Applications with ASP.NET

2.0Chaostage, Deggenbdorf

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Who I amWho 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

AgendaAgenda

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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Simplified Data BindingSimplified 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") %>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

DataSource ControlsDataSource 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

SqlDataSourceSqlDataSource

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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Using SqlDataSourceUsing SqlDataSource

<asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [Id], [Name], [Email] FROM [Customer]" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" /> <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>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Key SqlDataSource PropertiesKey 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)

© 2005 newtelligence Aktiengesellschaft. All rights reserved

SqlDataSource and CachingSqlDataSource 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

© 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 ResultsCaching Results

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Parameterized CommandsParameterized 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Parameters PropertiesParameters 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Parameter TypesParameter 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Using ControlParameterUsing 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> ......

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Calling Stored ProceduresCalling Stored Procedures

CREATE PROCEDURE proc_GetCustomers@Country nvarchar (32) AS SELECT * FROM Customers WHERE Country = @CountryGO

<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" />

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Using the SqlDataSourceUsing the SqlDataSource

© 2005 newtelligence Aktiengesellschaft. All rights reserved

XmlDataSourceXmlDataSource

Declarative data binding to XML data Supports caching and XSLT One-way data binding only

•no updating :-(

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Key XmlDataSource PropertiesKey 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)

© 2005 newtelligence Aktiengesellschaft. All rights reserved

XmlDataSourceXmlDataSource

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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Using the XmlDataSourceUsing the XmlDataSource

© 2005 newtelligence Aktiengesellschaft. All rights reserved

ObjectDataSourceObjectDataSource

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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Key ObjectDataSource PropertiesKey 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Key ObjectDataSource Properties IIKey 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Initialization and Clean-UpInitialization 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Using the ObjectDataSourceUsing the ObjectDataSource

© 2005 newtelligence Aktiengesellschaft. All rights reserved

The GridView ControlThe 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

GridView Field TypesGridView 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Specifying Field TypesSpecifying 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>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

The DetailsView ControlThe 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

DetailsView ExampleDetailsView 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>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Master-Detail ViewsMaster-Detail Views

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Inserting, Updating, and DeletingInserting, 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

© 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 GridViewsEditing with GridViews

Edit buttons Primary key

Update command Update parameters

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Conflict DetectionConflict 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"

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Optimistic Concurrency UpdatesOptimistic 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" />

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Last-In-Wins UpdatesLast-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" />

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Error DetectionError 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Handling Update ErrorsHandling 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 }}

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Editing with GridView and DetailsViewEditing with GridView and DetailsView

© 2005 newtelligence Aktiengesellschaft. All rights reserved

XML SupportXML 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

XML data type

•Native SQL type

Well-formed and validation checksOptional XML Schema enforcementBehaviours allow XQuery and

extensions

•Exist, Query, Modify, Value

Native XML StoreXML Data TypeNative XML StoreXML Data Type

© 2005 newtelligence Aktiengesellschaft. All rights reserved

SQL Cache DependenciesSQL 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

aspnet_regsql.exe -S localhost -E -d Northwind -ed

Preparing a DatabasePreparing a Database

Use Aspnet_regsql.exe or SqlCache-DependencyAdmin to prepare database*

Trusted connectionDatabase nameEnable database

* Not necessary for SQL Server 2005

Server name

© 2005 newtelligence Aktiengesellschaft. All rights reserved

aspnet_regsql -S localhost -E -d Northwind –t Products -ed

Preparing a TablePreparing a Table

Use Aspnet_regsql.exe or SqlCache-DependencyAdmin to prepare table*

Trusted connectionDatabase nameTable name

Server name

Enable table* Not necessary for SQL Server 2005

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Preparing Web.configPreparing 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>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Cache.Insert ("Products", products, new SqlCacheDependency ("Northwind", "Products");

Using SqlCacheDependency with the Application CacheUsing SqlCacheDependency with the Application Cache

Database name

Table name

© 2005 newtelligence Aktiengesellschaft. All rights reserved

<%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %>

Using SqlCacheDependency with the Output CacheUsing SqlCacheDependency with the Output Cache

Database name

Table name

© 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 SqlDataSourceUsing SqlCacheDependency with SqlDataSource

Database name

Table name

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Cache ConfigurationCache 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>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

SqlDependencySqlDependency

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){}

© 2005 newtelligence Aktiengesellschaft. All rights reserved

SQL Cache DependenciesSQL Cache Dependencies

© 2005 newtelligence Aktiengesellschaft. All rights reserved

ConnectionStringBuilderConnectionStringBuilder

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);

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Securing Connection StringsSecuring Connection Strings

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">

<EncryptedData>

<CipherData>

<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA4rwj++4ocEqWto+xX+GfmQQAAAACAAAAAAADZgAAqAAAABAAAAAAenfLPcbvaitCjiKB/JM+AAAAAASAAACgAAAAEAAAAKCmuCXyu0Mor8UIouCX/6xwAQAAzyodkmx05YVrgZF3Jp/6KrcpBfw3k6D1vNi8DE/neOsXwfZ2Terw0eSgHlaFX/q4Q+uoBy2imBlO9z+tGBmS1SDDietOgLFVPBd0M/AHUoBnNihFjh2RocoBuZltF3+albLYAnDwbE6QZ0/Pdm9VKB24Wv1OMZSL9Re+rQOlpuCfN2Y0T97h5xVlH4qMHlquCvehiZcjqaG8ZqdLh5gQd8uZHClyG7Dc70/4bzaE/cI+CLzKtUtLOcWj8cpQ3Y9xnKB7GdyxE9L94ofyeA99uOLT02sO3OoOjZPyGGd651Xrkqb9eGvx3RfHqwnbKTDMf39AxIsbEu1qebA7tsATM/shc/X5nrukL+6VWBxzgP5JS1PM6jMzOmCtloMRb0Om3bsaoc4yBPaiKM6p02LwvwB8C2w/VaI501a5iBQ+MX2aOn1uF8b+Gb3zDWWLpqC+6m80Zflza5WuoqYVGrUGPkS0r1E5b6pGwZnm0XOXRKoUAAAASQxsCa2kp8XwDllVsC2Pq/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");

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Securing Connection StringsSecuring Connection Strings

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Factory Class HierarchyFactory Class Hierarchy

IDb* interfaces (e.g. IDbConnection)

Db* abstract base classes (e.g. DbConnection)

Db*Base implementation classes

Sql OleDb ODBC Oracle3rd

Party 13rd

Party 2

Provider-Independent apps code to this layer

Provider-specific apps code to this layer

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Using a Provider FactoryUsing 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()

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Connection PoolingConnection 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");

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Asynchronous CommandsAsynchronous Commands

Ideal for multiple database queriesUsual Beginxxx and Endxxx modelSupports Polling, Wait and Callback

modelsCatching asynchronous execution errorsShould not generally be used with MARS

•use a separate connection for each Command

Add "async=true" to connection string

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Asynchronous Polling ModelAsynchronous 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 )

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Asynchronous Callback ModelAsynchronous 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);

}

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Promotable TransactionsPromotable 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Auto-promoting a TransactionAuto-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();

© 2005 newtelligence Aktiengesellschaft. All rights reserved

DataSet or Not DataSet?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"/>

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Asynchronous Callback ModelAsynchronous 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);

}

© 2005 newtelligence Aktiengesellschaft. All rights reserved

When To Use DataSetWhen 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

DataSet and CachingDataSet 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Alternatives – DataReaderAlternatives – 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Alternatives – DataReader, DataTableAlternatives – 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

© 2005 newtelligence Aktiengesellschaft. All rights reserved

© 2005 newtelligence Aktiengesellschaft. All rights reserved

Thank YouThank You

© 2005 newtelligence® Aktiengesellschaft

newtelligence® AGGilleshütte 99D-41352 Korschenbroichhttp://www.newtelligence.cominfo@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.

top related