SlideShare a Scribd company logo
1 of 70
Download to read offline
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
© 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
© 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
© 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") %>
© 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
© 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
© 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>
© 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)
© 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
© 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
© 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
© 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
© 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
© 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>
......
© 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" />
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Using the SqlDataSource
© 2005 newtelligence Aktiengesellschaft. All rights reserved
XmlDataSource
 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 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
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>
...
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Using the XmlDataSource
© 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
© 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
© 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
© 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
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Using the ObjectDataSource
© 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
© 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
© 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>
© 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
© 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>
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Master-Detail Views
© 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
© 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
© 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"
© 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" />
© 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" />
© 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
© 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
}
}
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Editing with GridView and
DetailsView
© 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
© 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
© 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
© 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
© 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
© 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>
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Cache.Insert ("Products", products,
new SqlCacheDependency ("Northwind", "Products");
Using 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 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 SqlDataSource
Database name
Table name
© 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>
© 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)
{
}
© 2005 newtelligence Aktiengesellschaft. All rights reserved
SQL Cache Dependencies
© 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);
© 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");
© 2005 newtelligence Aktiengesellschaft. All rights reserved
Securing Connection Strings
© 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
© 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()
© 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");
© 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
© 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 )
© 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);
}
© 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
© 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();
© 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"
/>
© 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);
}
© 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
© 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
© 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
© 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
© 2005 newtelligence Aktiengesellschaft. All rights reserved
© 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.

More Related Content

What's hot

OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)Apigee | Google Cloud
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desaijmsthakur
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesArvind Krishnaa
 
Itemscript, a specification for RESTful JSON integration
Itemscript, a specification for RESTful JSON integrationItemscript, a specification for RESTful JSON integration
Itemscript, a specification for RESTful JSON integration{item:foo}
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.netNgeam Soly
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 
10.Local Database & LINQ
10.Local Database & LINQ10.Local Database & LINQ
10.Local Database & LINQNguyen Tuan
 
OData and SharePoint
OData and SharePointOData and SharePoint
OData and SharePointSanjay Patel
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPAShaun Smith
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Rob Windsor
 

What's hot (20)

For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)OData Introduction and Impact on API Design (Webcast)
OData Introduction and Impact on API Design (Webcast)
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View Classes
 
B_110500002
B_110500002B_110500002
B_110500002
 
Itemscript, a specification for RESTful JSON integration
Itemscript, a specification for RESTful JSON integrationItemscript, a specification for RESTful JSON integration
Itemscript, a specification for RESTful JSON integration
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
E script
E scriptE script
E script
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
10.Local Database & LINQ
10.Local Database & LINQ10.Local Database & LINQ
10.Local Database & LINQ
 
OData and SharePoint
OData and SharePointOData and SharePoint
OData and SharePoint
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPA
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
Olap
OlapOlap
Olap
 
Odata
OdataOdata
Odata
 

Viewers also liked

2013 - ICE Lingen: AngularJS introduction
2013 - ICE Lingen: AngularJS introduction2013 - ICE Lingen: AngularJS introduction
2013 - ICE Lingen: AngularJS introductionDaniel Fisher
 
2014 - DotNetCologne: Build, Builder, Am Buildesten
2014 - DotNetCologne: Build, Builder, Am Buildesten2014 - DotNetCologne: Build, Builder, Am Buildesten
2014 - DotNetCologne: Build, Builder, Am BuildestenDaniel Fisher
 
2014 - DotNet UG Rhen Ruhr: Komponentenorientierung
2014 - DotNet UG Rhen Ruhr: Komponentenorientierung2014 - DotNet UG Rhen Ruhr: Komponentenorientierung
2014 - DotNet UG Rhen Ruhr: KomponentenorientierungDaniel Fisher
 
2011 - DotNetFranken: ASP.NET MVC Localization
2011 - DotNetFranken: ASP.NET MVC Localization2011 - DotNetFranken: ASP.NET MVC Localization
2011 - DotNetFranken: ASP.NET MVC LocalizationDaniel Fisher
 
Jan Lokpal VS Sarkari Lokpal
Jan Lokpal VS Sarkari LokpalJan Lokpal VS Sarkari Lokpal
Jan Lokpal VS Sarkari LokpalAnoochan Pandey
 
2015 JavaScript introduction
2015 JavaScript introduction2015 JavaScript introduction
2015 JavaScript introductionDaniel Fisher
 
2009 - NRW Conf: (ASP).NET Membership
2009 - NRW Conf: (ASP).NET Membership2009 - NRW Conf: (ASP).NET Membership
2009 - NRW Conf: (ASP).NET MembershipDaniel Fisher
 
2009 - Microsoft Springbreak: IIS, PHP & WCF
2009 - Microsoft Springbreak: IIS, PHP & WCF2009 - Microsoft Springbreak: IIS, PHP & WCF
2009 - Microsoft Springbreak: IIS, PHP & WCFDaniel Fisher
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#Daniel Fisher
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageabilityDaniel Fisher
 
2015 DWX - Komponenten und Konsequenzen
2015 DWX - Komponenten und Konsequenzen2015 DWX - Komponenten und Konsequenzen
2015 DWX - Komponenten und KonsequenzenDaniel Fisher
 
Saturation vs satisfaction in it industry
Saturation vs satisfaction in it industrySaturation vs satisfaction in it industry
Saturation vs satisfaction in it industryChirabrata Majumder
 
2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...
2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...
2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...Daniel Fisher
 
2006 DDD4: Data access layers - Convenience vs. Control and Performance?
2006 DDD4: Data access layers - Convenience vs. Control and Performance?2006 DDD4: Data access layers - Convenience vs. Control and Performance?
2006 DDD4: Data access layers - Convenience vs. Control and Performance?Daniel Fisher
 
2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...
2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...
2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...Daniel Fisher
 
2006 - Basta!: Web 2.0 mit asp.net 2.0
2006 - Basta!: Web 2.0 mit asp.net 2.02006 - Basta!: Web 2.0 mit asp.net 2.0
2006 - Basta!: Web 2.0 mit asp.net 2.0Daniel Fisher
 
2008 - Afterlaunch: 10 Tipps für WCF
2008 - Afterlaunch: 10 Tipps für WCF2008 - Afterlaunch: 10 Tipps für WCF
2008 - Afterlaunch: 10 Tipps für WCFDaniel Fisher
 

Viewers also liked (20)

2013 - ICE Lingen: AngularJS introduction
2013 - ICE Lingen: AngularJS introduction2013 - ICE Lingen: AngularJS introduction
2013 - ICE Lingen: AngularJS introduction
 
2014 - DotNetCologne: Build, Builder, Am Buildesten
2014 - DotNetCologne: Build, Builder, Am Buildesten2014 - DotNetCologne: Build, Builder, Am Buildesten
2014 - DotNetCologne: Build, Builder, Am Buildesten
 
2014 - DotNet UG Rhen Ruhr: Komponentenorientierung
2014 - DotNet UG Rhen Ruhr: Komponentenorientierung2014 - DotNet UG Rhen Ruhr: Komponentenorientierung
2014 - DotNet UG Rhen Ruhr: Komponentenorientierung
 
2011 - DotNetFranken: ASP.NET MVC Localization
2011 - DotNetFranken: ASP.NET MVC Localization2011 - DotNetFranken: ASP.NET MVC Localization
2011 - DotNetFranken: ASP.NET MVC Localization
 
Hindi Jan Lokpal
Hindi Jan LokpalHindi Jan Lokpal
Hindi Jan Lokpal
 
Jan Lokpal VS Sarkari Lokpal
Jan Lokpal VS Sarkari LokpalJan Lokpal VS Sarkari Lokpal
Jan Lokpal VS Sarkari Lokpal
 
2015 JavaScript introduction
2015 JavaScript introduction2015 JavaScript introduction
2015 JavaScript introduction
 
2009 - NRW Conf: (ASP).NET Membership
2009 - NRW Conf: (ASP).NET Membership2009 - NRW Conf: (ASP).NET Membership
2009 - NRW Conf: (ASP).NET Membership
 
2009 - Microsoft Springbreak: IIS, PHP & WCF
2009 - Microsoft Springbreak: IIS, PHP & WCF2009 - Microsoft Springbreak: IIS, PHP & WCF
2009 - Microsoft Springbreak: IIS, PHP & WCF
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
 
2015 DWX - Komponenten und Konsequenzen
2015 DWX - Komponenten und Konsequenzen2015 DWX - Komponenten und Konsequenzen
2015 DWX - Komponenten und Konsequenzen
 
Pļavu bibliotēka
Pļavu bibliotēkaPļavu bibliotēka
Pļavu bibliotēka
 
Saturation vs satisfaction in it industry
Saturation vs satisfaction in it industrySaturation vs satisfaction in it industry
Saturation vs satisfaction in it industry
 
2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...
2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...
2015 - Network 2015, UA: Defensive programming, resilience patterns & antifra...
 
2006 DDD4: Data access layers - Convenience vs. Control and Performance?
2006 DDD4: Data access layers - Convenience vs. Control and Performance?2006 DDD4: Data access layers - Convenience vs. Control and Performance?
2006 DDD4: Data access layers - Convenience vs. Control and Performance?
 
2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...
2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...
2015 - Basta! 2015, DE: Defensive programming, resilience patterns & antifrag...
 
2006 - Basta!: Web 2.0 mit asp.net 2.0
2006 - Basta!: Web 2.0 mit asp.net 2.02006 - Basta!: Web 2.0 mit asp.net 2.0
2006 - Basta!: Web 2.0 mit asp.net 2.0
 
2008 - Afterlaunch: 10 Tipps für WCF
2008 - Afterlaunch: 10 Tipps für WCF2008 - Afterlaunch: 10 Tipps für WCF
2008 - Afterlaunch: 10 Tipps für WCF
 
E waste cm-fassmta_2015
E waste cm-fassmta_2015E waste cm-fassmta_2015
E waste cm-fassmta_2015
 

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

Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Igor Moochnick
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Servicesukdpe
 
Enterprise Library 2.0
Enterprise Library 2.0Enterprise Library 2.0
Enterprise Library 2.0Raju Permandla
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5Tieturi Oy
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoHasnain Iqbal
 
Expanding your impact with programmability in the data center
Expanding your impact with programmability in the data centerExpanding your impact with programmability in the data center
Expanding your impact with programmability in the data centerCisco Canada
 
Wcf data services
Wcf data servicesWcf data services
Wcf data servicesEyal Vardi
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...goodfriday
 
“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools
“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools
“Lights Out”Configuration using Tivoli Netcool AutoDiscovery ToolsAntonio Rolle
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaSonu Vishwakarma
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath CommunityRohit Radhakrishnan
 
SQL Server 2008 Positioning
SQL Server 2008 PositioningSQL Server 2008 Positioning
SQL Server 2008 Positioningukdpe
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklum Ukraine
 
Decomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDecomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDennis Doomen
 
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling Sencha
 

Similar to 2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0 (20)

Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
 
Dev411
Dev411Dev411
Dev411
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Services
 
Enterprise Library 2.0
Enterprise Library 2.0Enterprise Library 2.0
Enterprise Library 2.0
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 
ASP
ASPASP
ASP
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 
Scale By The Bay | 2020 | Gimel
Scale By The Bay | 2020 | GimelScale By The Bay | 2020 | Gimel
Scale By The Bay | 2020 | Gimel
 
Expanding your impact with programmability in the data center
Expanding your impact with programmability in the data centerExpanding your impact with programmability in the data center
Expanding your impact with programmability in the data center
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
Asp db
Asp dbAsp db
Asp db
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
 
“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools
“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools
“Lights Out”Configuration using Tivoli Netcool AutoDiscovery Tools
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu Vishwakarma
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
 
SQL Server 2008 Positioning
SQL Server 2008 PositioningSQL Server 2008 Positioning
SQL Server 2008 Positioning
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
 
Dev308
Dev308Dev308
Dev308
 
Decomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDecomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservices
 
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
 

More from Daniel Fisher

MD DevdDays 2016: Defensive programming, resilience patterns & antifragility
MD DevdDays 2016: Defensive programming, resilience patterns & antifragilityMD DevdDays 2016: Defensive programming, resilience patterns & antifragility
MD DevdDays 2016: Defensive programming, resilience patterns & antifragilityDaniel Fisher
 
NRWConf, DE: Defensive programming, resilience patterns & antifragility
NRWConf, DE: Defensive programming, resilience patterns & antifragilityNRWConf, DE: Defensive programming, resilience patterns & antifragility
NRWConf, DE: Defensive programming, resilience patterns & antifragilityDaniel Fisher
 
.NET Developer Days 2015, PL: Defensive programming, resilience patterns & an...
.NET Developer Days 2015, PL: Defensive programming, resilience patterns & an....NET Developer Days 2015, PL: Defensive programming, resilience patterns & an...
.NET Developer Days 2015, PL: Defensive programming, resilience patterns & an...Daniel Fisher
 
2015 - Basta! 2015, DE: JavaScript und build
2015 - Basta! 2015, DE: JavaScript und build2015 - Basta! 2015, DE: JavaScript und build
2015 - Basta! 2015, DE: JavaScript und buildDaniel Fisher
 
2011 - Dotnet Information Day: NUGET
2011 - Dotnet Information Day: NUGET2011 - Dotnet Information Day: NUGET
2011 - Dotnet Information Day: NUGETDaniel Fisher
 
2011 - DNC: REST Wars
2011 - DNC: REST Wars2011 - DNC: REST Wars
2011 - DNC: REST WarsDaniel Fisher
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5Daniel Fisher
 
2010 - Basta!: REST mit WCF 4, Silverlight und AJAX
2010 - Basta!: REST mit WCF 4, Silverlight und AJAX2010 - Basta!: REST mit WCF 4, Silverlight und AJAX
2010 - Basta!: REST mit WCF 4, Silverlight und AJAXDaniel Fisher
 
2010 - Basta!: IPhone Apps mit C#
2010 - Basta!: IPhone Apps mit C#2010 - Basta!: IPhone Apps mit C#
2010 - Basta!: IPhone Apps mit C#Daniel Fisher
 
2010 - Basta: ASP.NET Controls für Web Forms und MVC
2010 - Basta: ASP.NET Controls für Web Forms und MVC2010 - Basta: ASP.NET Controls für Web Forms und MVC
2010 - Basta: ASP.NET Controls für Web Forms und MVCDaniel Fisher
 
2010 Basta!: Massendaten mit ADO.NET
2010 Basta!: Massendaten mit ADO.NET2010 Basta!: Massendaten mit ADO.NET
2010 Basta!: Massendaten mit ADO.NETDaniel Fisher
 
2010 - Basta!: REST mit ASP.NET MVC
2010 - Basta!: REST mit ASP.NET MVC2010 - Basta!: REST mit ASP.NET MVC
2010 - Basta!: REST mit ASP.NET MVCDaniel Fisher
 
2009 - DNC: Silverlight ohne UI - Nur als Cache
2009 - DNC: Silverlight ohne UI - Nur als Cache2009 - DNC: Silverlight ohne UI - Nur als Cache
2009 - DNC: Silverlight ohne UI - Nur als CacheDaniel Fisher
 
2009 - Basta!: Url rewriting mit iis, asp.net und routing engine
2009 - Basta!: Url rewriting mit iis, asp.net und routing engine2009 - Basta!: Url rewriting mit iis, asp.net und routing engine
2009 - Basta!: Url rewriting mit iis, asp.net und routing engineDaniel Fisher
 
2009 - Basta!: Agiles requirements engineering
2009 - Basta!: Agiles requirements engineering2009 - Basta!: Agiles requirements engineering
2009 - Basta!: Agiles requirements engineeringDaniel Fisher
 
2008 - TechDays PT: Modeling and Composition for Software today and tomorrow
2008 - TechDays PT: Modeling and Composition for Software today and tomorrow2008 - TechDays PT: Modeling and Composition for Software today and tomorrow
2008 - TechDays PT: Modeling and Composition for Software today and tomorrowDaniel Fisher
 
2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with Volta2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with VoltaDaniel Fisher
 
2008 - Basta!: DAL DIY
2008 - Basta!: DAL DIY2008 - Basta!: DAL DIY
2008 - Basta!: DAL DIYDaniel Fisher
 
2008 - Basta!: Massendaten auf dem Client
2008 - Basta!: Massendaten auf dem Client2008 - Basta!: Massendaten auf dem Client
2008 - Basta!: Massendaten auf dem ClientDaniel Fisher
 
2007 - Basta!: Nach soa kommt soc
2007 - Basta!: Nach soa kommt soc2007 - Basta!: Nach soa kommt soc
2007 - Basta!: Nach soa kommt socDaniel Fisher
 

More from Daniel Fisher (20)

MD DevdDays 2016: Defensive programming, resilience patterns & antifragility
MD DevdDays 2016: Defensive programming, resilience patterns & antifragilityMD DevdDays 2016: Defensive programming, resilience patterns & antifragility
MD DevdDays 2016: Defensive programming, resilience patterns & antifragility
 
NRWConf, DE: Defensive programming, resilience patterns & antifragility
NRWConf, DE: Defensive programming, resilience patterns & antifragilityNRWConf, DE: Defensive programming, resilience patterns & antifragility
NRWConf, DE: Defensive programming, resilience patterns & antifragility
 
.NET Developer Days 2015, PL: Defensive programming, resilience patterns & an...
.NET Developer Days 2015, PL: Defensive programming, resilience patterns & an....NET Developer Days 2015, PL: Defensive programming, resilience patterns & an...
.NET Developer Days 2015, PL: Defensive programming, resilience patterns & an...
 
2015 - Basta! 2015, DE: JavaScript und build
2015 - Basta! 2015, DE: JavaScript und build2015 - Basta! 2015, DE: JavaScript und build
2015 - Basta! 2015, DE: JavaScript und build
 
2011 - Dotnet Information Day: NUGET
2011 - Dotnet Information Day: NUGET2011 - Dotnet Information Day: NUGET
2011 - Dotnet Information Day: NUGET
 
2011 - DNC: REST Wars
2011 - DNC: REST Wars2011 - DNC: REST Wars
2011 - DNC: REST Wars
 
2011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 52011 NetUG HH: ASP.NET MVC & HTML 5
2011 NetUG HH: ASP.NET MVC & HTML 5
 
2010 - Basta!: REST mit WCF 4, Silverlight und AJAX
2010 - Basta!: REST mit WCF 4, Silverlight und AJAX2010 - Basta!: REST mit WCF 4, Silverlight und AJAX
2010 - Basta!: REST mit WCF 4, Silverlight und AJAX
 
2010 - Basta!: IPhone Apps mit C#
2010 - Basta!: IPhone Apps mit C#2010 - Basta!: IPhone Apps mit C#
2010 - Basta!: IPhone Apps mit C#
 
2010 - Basta: ASP.NET Controls für Web Forms und MVC
2010 - Basta: ASP.NET Controls für Web Forms und MVC2010 - Basta: ASP.NET Controls für Web Forms und MVC
2010 - Basta: ASP.NET Controls für Web Forms und MVC
 
2010 Basta!: Massendaten mit ADO.NET
2010 Basta!: Massendaten mit ADO.NET2010 Basta!: Massendaten mit ADO.NET
2010 Basta!: Massendaten mit ADO.NET
 
2010 - Basta!: REST mit ASP.NET MVC
2010 - Basta!: REST mit ASP.NET MVC2010 - Basta!: REST mit ASP.NET MVC
2010 - Basta!: REST mit ASP.NET MVC
 
2009 - DNC: Silverlight ohne UI - Nur als Cache
2009 - DNC: Silverlight ohne UI - Nur als Cache2009 - DNC: Silverlight ohne UI - Nur als Cache
2009 - DNC: Silverlight ohne UI - Nur als Cache
 
2009 - Basta!: Url rewriting mit iis, asp.net und routing engine
2009 - Basta!: Url rewriting mit iis, asp.net und routing engine2009 - Basta!: Url rewriting mit iis, asp.net und routing engine
2009 - Basta!: Url rewriting mit iis, asp.net und routing engine
 
2009 - Basta!: Agiles requirements engineering
2009 - Basta!: Agiles requirements engineering2009 - Basta!: Agiles requirements engineering
2009 - Basta!: Agiles requirements engineering
 
2008 - TechDays PT: Modeling and Composition for Software today and tomorrow
2008 - TechDays PT: Modeling and Composition for Software today and tomorrow2008 - TechDays PT: Modeling and Composition for Software today and tomorrow
2008 - TechDays PT: Modeling and Composition for Software today and tomorrow
 
2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with Volta2008 - TechDays PT: Building Software + Services with Volta
2008 - TechDays PT: Building Software + Services with Volta
 
2008 - Basta!: DAL DIY
2008 - Basta!: DAL DIY2008 - Basta!: DAL DIY
2008 - Basta!: DAL DIY
 
2008 - Basta!: Massendaten auf dem Client
2008 - Basta!: Massendaten auf dem Client2008 - Basta!: Massendaten auf dem Client
2008 - Basta!: Massendaten auf dem Client
 
2007 - Basta!: Nach soa kommt soc
2007 - Basta!: Nach soa kommt soc2007 - Basta!: Nach soa kommt soc
2007 - Basta!: Nach soa kommt soc
 

Recently uploaded

Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilVICTOR MAESTRE RAMIREZ
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.Sharon Liu
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorShane Coughlan
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLAlluxio, Inc.
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampVICTOR MAESTRE RAMIREZ
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfBrain Inventory
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 

Recently uploaded (20)

Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-Council
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
Kawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in TrivandrumKawika Technologies pvt ltd Software Development Company in Trivandrum
Kawika Technologies pvt ltd Software Development Company in Trivandrum
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS Calculator
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
Deep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - DatacampDeep Learning for Images with PyTorch - Datacamp
Deep Learning for Images with PyTorch - Datacamp
 
Salesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptxSalesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptx
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdf
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 

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

  • 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. © 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. © 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 <!-- 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. © 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="<%$ 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. © 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 <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. © 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 <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. © 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. © 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 <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. © 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 <Columns> 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 <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. © 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. © 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. © 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 <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. © 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 <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. © 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. © 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 <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. © 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 <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. © 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 <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. © 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 <%@ OutputCache Duration="60" VaryByParam="None" SqlDependency="Northwind:Products" %> Using SqlCacheDependency with the Output Cache Database name Table name
  • 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. © 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. © 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 <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. © 2005 newtelligence Aktiengesellschaft. All rights reserved Securing Connection Strings
  • 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 2005 newtelligence Aktiengesellschaft. All rights reserved
  • 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.

Editor's Notes

  1. Developers new to ASP.NET are likely to find the new &amp;quot;Eval&amp;quot; syntax less intimidating than the old. In addition, the new XPath and XPathSelect operators (the latter of which is not shown here) provide a convenient mechanism for targeting data in XML data sources.
  2. Data source controls reduce the amount of code you write by replacing code that queries data sources and binds the results to controls with &amp;lt;asp:&amp;gt; tags. In Visual Studio 2005, you can create these tags using drag-and-drop. You can also use the Visual Studio IDE to configure data sources. The first four data source controls listed in this table are introduced in this lecture; the final one (SiteMapDataSource) is introduced in the Site Navigation module since it&amp;apos;s a special-purpose control that&amp;apos;s specifically designed to interface with site maps. NOTE: Beta 1 contains an additional data source control named DataSetDataSource. That control will be dropped from beta 2 (too much overlap with XmlDataSource), so it isn&amp;apos;t mentioned here.
  3. SqlDataSource isn&amp;apos;t limited to SQL Server databases; it can connect to any database served by a managed provider, including Oracle databases.
  4. In this example (and others in this deck), the connection string is hard-coded into the ASPX file. In practice, you should put connection strings in the &amp;lt;connectionStrings&amp;gt; section of Web.config instead and load them with $ expressions. Among other things, putting connection strings in Web.config gives you the option of encrypting them.
  5. SqlDataSource implements LOTS of public properties. These are some of the ones that developers are most likely to use, and ones that unlock some of SqlDataSource&amp;apos;s key features. In particular, SelectCommand defines the query that a SqlDataSource uses to fetch data from a database, while InsertCommand, UpdateCommand, and DeleteCommand define the commands it uses to update the database when 2-way data binding is performed. InsertCommand, UpdateCommand, and DeleteCommand are discussed in detail later in this lecture.
  6. Note that EnableCaching=&amp;quot;true&amp;quot; is only valid if DataSourceMode=&amp;quot;DataSet&amp;quot;. That&amp;apos;s because DataSets can be cached but DataReaders cannot. DataSourceMode=&amp;quot;DataSet&amp;quot; is the default, but if you&amp;apos;re not caching, you can make SqlDataSource slightly more efficient by setting DataSourceMode=&amp;quot;DataReader.&amp;quot;
  7. Caching is enabled by setting EnableCaching=&amp;quot;true&amp;quot; and CacheDuration to the number of seconds you want the data cached. In this example, the SqlDataSource caches its query results for up to 1 minute (60 seconds) at a time. Under the hood, SqlDataSource uses the ASP.NET application cache to store the data, so the cached data could be removed from the cache before 60 seconds is up if ASP.NET senses memory pressure on the server and decides to evict items from the cache early in order to reclaim memory.
  8. Data source controls would have limited value if SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand could not be parameterized. A great example is the case where data displayed in a GridView is keyed to the value currently selected in a DropDownList. In that case, the SqlDataSource serving the GridView needs a SelectCommand containing a WHERE clause with a replaceable parameter whose value comes from the DropDownList. Fortunately, this scenario is supported, meaning SqlDataSource controls can perform SELECTs, INSERTs, UPDATEs, and DELETEs of arbitrary complexity.
  9. The SelectParameters, InsertParameters, UpdateParameters, and DeleteParameters properties provide a handy mechanism for declaratively adding parameters to a SqlDataSource&amp;apos;s SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand. FilterParameters defines parameters for SqlDataSource.FilterExpression. FilterExpression filters the data returned by SelectCommand. On the surface, it might seem as if defining a FilterExpression is no different than including a WHERE clause in a SelectCommand. However, FilterExpression works even if the SqlDataSource is caching query results.
  10. These types are used with SelectParameters, InsertParameters, UpdateParameters, DeleteParameters, and FilterParameters to define where the values for replaceable parameters come from. ControlParameter, for example, keys a replaceable parameter in a database command to a value in a control. QueryStringParameter, on the other hand, keys a replaceable parameter to a value in a query string.
  11. This example uses the value of the item currently selected in a drop-down list to fill a parameter in a SELECT statement&amp;apos;s WHERE clause. Note the &amp;lt;SelectParameters&amp;gt; element adding parameters to SelectCommand, and the &amp;lt;asp:ControlParameter&amp;gt; element corresponding to the @Country parameter in the SelectCommand. If SelectCommand contained additional parameters, &amp;lt;SelectParameters&amp;gt; would contain additional &amp;lt;asp:XxxParameter&amp;gt; elements.
  12. A common question regarding SqlDataSource controls is &amp;quot;Can they call stored procedures?&amp;quot; The answer is yes, and this example demonstrates how. One of the stored procedures used in the example has no parameters. The other has a SELECT parameter, so a &amp;lt;SelectParameters&amp;gt; element is used to tie the value of that parameter to the item selected in a drop-down list. This example is functionally equivalent to the one on the previous slide.
  13. XmlDataSource is functionally similar to SqlDataSource, but it&amp;apos;s designed to read data from XML data sources rather than databases. One use for XmlDataSource is to read hierarchical data from an XML file and then render that data using a TreeView control, as shown here.
  14. The DataFile and TransformFile properties refer to files containing XML and XSL data. XmlDataSource has complementary properties named Data and Transform that allow XML and XSL to be loaded from strings. Not surprisingly, you use XPath expressions to filter data in an XmlDataSource. Using the XPath property of an XmlDataSource is morally equivalent to using the FilterExpression property of a SqlDataSource.
  15. Next to SqlDataSource, ObjectDataSource is probably the data source control that will garner the most attention from developers. Many applications (especially multi-tier applications) isolate logic for talking to databases and other data sources in a data access layer, the goal being to isolate the UI layer from changes that occur to the data source on the back end. ObjectDataSource permits you to practice declarative data binding without sacrificing the ability to use middle-tier data access components to access data sources. The downside to SqlDataSource is that it creates an explicit connection between code in the UI layer and the data on the back end. ObjectDataSource provides a solution to that problem.
  16. Besides the SelectMethod, InsertMethod, UpdateMethod, and DeleteMethod properties, which identify the methods than an ObjectDataSource calls on a data component to perform SELECTs, INSERTs, UPDATEs, and DELETEs, the most important property in an ObjectDataSource is the TypeName property, which identifies the data component&amp;apos;s type (class). ObjectDataSource uses TypeName to instantiate the data component, or, in the case where SelectMethod, InsertMethod, UpdateMethod, or DeleteMethod identifies a static method, to determine what type name to prefix method calls with.
  17. ObjectDataSources can use parameterized commands like SqlDataSources, as evidenced by the presence of the SelectParameters, InsertParameters, UpdateParameters, and DeleteParameters properties. They also support caching like SqlDataSources.
  18. The fact that ObjectDataSource creates a new instance of the data component that it wraps on each call has significant performance implications if the data component does time-consuming work at creation time. The solution to that problem is to use static methods instead of instance methods, since static methods don&amp;apos;t require that a class instance be created. ObjectDataSource fires an ObjectCreated event after creating an instance of the data component that it wraps. You can process this event to custom-initialize the data component right after it&amp;apos;s created. Similarly, ObjectDataSource fires an ObjectDisposing event just before disposing of the data component IF the data component implements IDisposable. You can process this event and do clean-up work of your own before the data component&amp;apos;s Dispose method is called.
  19. GridView is best described as a super DataGrid: it does everything DataGrid does and then some. Unlike the DataGrid, which requires code to do sorting, paging, selecting, and editing, the GridView control can perform all these actions innately--that is, with no code. GridView also supports a richer assortment of column types than DataGrid. The ImageField column type, for example, enables GridViews to display images--something the DataGrid requires help to do.
  20. GridView field types are analogous to DataGrid column types. CheckBoxField and ImageField are especially significant because there are no equivalent DataGrid column types.
  21. Just as DataGrids can be customized by setting AutoGenerateColumns=&amp;quot;false&amp;quot; and declaring columns in a &amp;lt;Columns&amp;gt; element, GridViews can be customized by setting AutoGenerateColumns=&amp;quot;false&amp;quot; and declaring fields in a &amp;lt;Columns&amp;gt; element. This example uses an ImageField column to display employee photos obtained from Northwind&amp;apos;s Employees table, a TemplateField to combine first names and last names, and a BoundField to display the contents of each record&amp;apos;s &amp;quot;Title&amp;quot; field. The output appears on the next slide.
  22. Whereas GridView is designed to render sets of records into HTML tables, DetailsView is designed to take one record or a set of records and display them one at a time. Built-in paging support enables records bound to a DetailsView to be browsed with no code. Built-in editing support allows records to be inserted, updated, and deleted, again with no code (although the reality is that you&amp;apos;ll end up writing some code to handle concurrency issues and respond to update failures). The same field types--ImageField, CheckBoxField, and so on--that can be declared in a GridView can also be declared in a DetailsView. In demonstrations, DetailsView controls are often paired with GridView controls to implement master-detail views. However, DetailsView is perfectly capable of working without GridView.
  23. This example declares a DetailsView control and uses a &amp;lt;Fields&amp;gt; element to declare the fields that the DetailsView displays. Like GridView, DetailsView automatically populates itself with fields if you leave AutoGenerateRows set to false (the default). The output appears on the next slide.
  24. RE: &amp;quot;Visual Studio supplies the glue.&amp;quot; There can be a lot of work involved in defining the InsertCommand, UpdateCommand, and DeleteCommand properties of a data source control, not to mention the InsertParameters, UpdateParameters, and DeleteParameters sections that accompany them. Visual Studio&amp;apos;s Configure Data Source command will do most of that work for you. It even lets you decide whether the UpdateCommands and DeleteCommands that it generates implement a first-in wins or last-in wins strategy, which determines what happens when multiple users edit the same data at the same time.
  25. This example demonstrates how to add Edit buttons to a GridView (AutoGenerateEditButton=&amp;quot;true&amp;quot;) and how to configure a SqlDataSource to support updates initiated by one of those buttons. UpdateCommand is structured so that the update succeeds even if one or more of the original fields are modified before the update takes place, commonly known as &amp;quot;last-in wins.&amp;quot; Note that no code is required to display an editing UI or invoke the data source&amp;apos;s UpdateCommand; all necessary logic is provided by the GridView.
  26. Concurrency issues complicate updates. What happens, for example, if two users edit the same data at the same time? The answer is driven by the data source control&amp;apos;s UpdateCommand. For example, update employees set lastname=@lastname, firstname=@firstname where employeeid=@original_employeeid implements a last-in-wins update strategy because updates succeed even if the original data has changed. By contrast, update employees set lastname=@lastname, firstname=@firstname where employeeid=@original_employeeid and lastname=@original_lastname and firstname=@original_firstname implements a first-in-wins update strategy because updates fail if the original data has changed. In addition to structuring UpdateCommands to implement the desired update strategy, data source controls also need you to set their ConflictDetection property to indicate which strategy you&amp;apos;ve chosen. Data source controls uses this property to determine whether to add parameters representing the fields&amp;apos; original values to the Parameters collection of the underyling Command object.
  27. In this example, UpdateCommand&amp;apos;s WHERE clause has been modified so that the update fails if any of the original fields are modified before the update takes place, commonly known as &amp;quot;first-in wins.&amp;quot; ConflictDetection=&amp;quot;CompareAllValues&amp;quot; instructs the SqlDataSource to include original_employeeid, original_lastname, and original_firstname parameters in the Parameters collection of the underlying Command object. While the need for these parameters could probably be inferred from the UpdateCommand in this example, inferring parameters is much harder with other data source types and other providers. As an aside, the &amp;quot;original_&amp;quot; prefix can be changed using the data source controls&amp;apos; OldValuesParameterFormatString property.
  28. In this example, UpdateCommand&amp;apos;s WHERE clause has been modified so that the update fails if any of the original fields are modified before the update takes place, commonly known as &amp;quot;first-in wins.&amp;quot; ConflictDetection=&amp;quot;CompareAllValues&amp;quot; instructs the SqlDataSource to include original_employeeid, original_lastname, and original_firstname parameters in the Parameters collection of the underlying Command object. While the need for these parameters could probably be inferred from the UpdateCommand in this example, inferring parameters is much harder with other data source types and other providers. As an aside, the &amp;quot;original_&amp;quot; prefix can be changed using the data source controls&amp;apos; OldValuesParameterFormatString property.
  29. When you edit data and submit the changes to the database on the back end, you have no guarantee that the updates will work. If you opt for a first-in-wins update strategy, for example, and user A submits changes before user B, user B&amp;apos;s update will fail (assuming, of course, that A and B are editing the same data). Robust applications respond elegantly to update failures. One way to handle update failures when using data and data source controls is to process the events that the controls fire following an attempt to update the database and see if the attempt succeeded. The event handlers receive &amp;quot;status&amp;quot; objects (for example, SqlDataSourceStatusEventArgs) denoting the outcome of the update. If the update attempt threw an exception, the status object reports the exception and lets you specify through its ExceptionHandled property whether the exception should be rethrown.
  30. If an update operation throws an exception, the SqlDataSource catches the exception and passes it to the Updated event handler in e.Exception. The update handler can determine whether an exception was thrown by checking e.Exception for null. If e.Exception != null, then by default the SqlDataSource will rethrow the exception when the event handler returns. If you&amp;apos;d prefer to handle the exception yourself, you can do so in the event handler and prevent the SqlDataSource from rethrowing the exception by setting e.ExceptionHandled to true.
  31. Why XML? Sparse, unstructured, hierarchical or recursive data Why store in SQL Server 2005? Transacted management, optimised queries, backup, interoperability, schema validation.
  32. SQL cache dependencies are one of ASP.NET 2.0&amp;apos;s coolest new features. In ASP.NET 1.x, you could place items in the application cache and create dependencies between those items and objects in the file system or other objects in the cache. Missing, however, was a means for creating dependencies between cached items and database entities, which would enable cached query results to be automatically evicted from the cache if the underlying data changes. SQL cache dependencies do exactly that.
  33. Enabling notifications for a database adds a table named AspNet_SqlCacheTablesForChangeNotification that ASP.NET polls to see if the table has been modified. It also adds stored procedures for polling the table, enabling tables to support cache dependencies, and more. Databases (and tables) can be prepared declaratively using the aspnet_regsql.exe admin tool or programmatically using the SqlCacheDependencyAdmin class. SqlCacheDependencyAdmin has methods named EnableNotifications and EnableTableForNotifications for enabling databases and tables for notifications. It also has methods for disabling notifications for databases and tables and enumerating tables that are enabled for notification. Internally, aspnet_regsql.exe uses SqlCacheDependencyAdmin to do its work.
  34. Enabling notifications for a table adds an insert/update/delete trigger to the table that writes to AspNet_SqlCacheTablesForChangeNotification when the table&amp;apos;s contents change. When a SqlCacheDependency refering to that table is created, ASP.NET polls the table periodically to check for changes. The polling interval is configured through the &amp;lt;sqlCacheDependency&amp;gt; element in Web.config.
  35. Once the database is prepared, SQL cache dependencies are enabled through Web.config. enabled=&amp;quot;true&amp;quot; enables them; pollTime=&amp;quot;5000&amp;quot; sets the polling interval to 5 seconds (5,000 milliseconds). For each database that you plan to use SQL cache dependencies with, you must add an &amp;lt;add&amp;gt; element to the &amp;lt;databases&amp;gt; section of the &amp;lt;sqlCacheDependency&amp;gt; element giving the database a name and identifying a connection string in the &amp;lt;connectionStrings&amp;gt; configuration section. The database name in the &amp;lt;add&amp;gt; element doesn&amp;apos;t have to be the actual database name; it&amp;apos;s a logical name used to create SqlCacheDependency objects (as demonstrated in the next three slides).
  36. &amp;quot;Database name&amp;quot; is the database name registered in the &amp;lt;databases&amp;gt; section of &amp;lt;sqlCacheDependency&amp;gt;, which may or may not equal the actual database name.
  37. ASP.NET&amp;apos;s @ OutputCache directive now supports a SqlDependency attribute enabling SQL cache dependencies to be created declaratively.
  38. When you use caching with data source controls, you can also use SQL cache dependencies to refresh the data source if and when the underlying data changes.
  39. ASP.NET 1.x provided very little control over cache settings. It was impossible, for example, to limit the output cache to a specified percentage of available memory. ASP.NET 2.0 fixes this error-by-omission by supporting a wide range of configuration settings for the application cache and the output cache. Ultimately, these configuration settings will be exposed through the ASP.NET MMC snap-in or the Web Site Administration Tool. However, it&amp;apos;s uncertain right now whether that will happen before ASP.NET 2.0 ships. For now, you can learn about these settings by examining the &amp;lt;caching&amp;gt; section of Machine.config.comments.