DataBinding in ASP.NET 2.0
description
Transcript of DataBinding in ASP.NET 2.0
Adam Calderon – C# MVPApplication Development Practice LeadInterKnowlogy
ADO.NET New FeaturesBinding Model Changes
DbProviderFactoriesSqlConnectionWeb.configSqlCommandTransactionScopeSqlDataAdaptorDataSet
CreateCommandCreateCommandBuilderCreateConnectionCreateDataAdaptorCreateParameter
// Data Comes from Inputs on Formstring provider = ProviderNameBox.Text;
string connString = ConnectionStringBox.Text; string commandText = CommandTextBox.Text;
// Get the provider DbProviderFactory fact = DbProviderFactories.GetFactory(provider);
// Create the connection DbConnection conn = fact.CreateConnection(); conn.ConnectionString = connString;
// Create the data adapter DbDataAdapter adapter = fact.CreateDataAdapter(); adapter.SelectCommand = conn.CreateCommand(); adapter.SelectCommand.CommandText = commandText;
// Run the query DataTable table = new DataTable(); adapter.Fill(table);
// Shows the results Results.DataSource = table; Results.DataBind();
Asynchronous Operation SupportFailover PartnerMultipleActiveResultSets (MARS)Connection String Builders
ConnectionStrings elementConfigurationManager.ConnectionStrings[“MySql”].ConnectionString
Protecting Connection Strings Use aspnet_regiis.exe to encrypt
web.config <protectedData>
<protectedDataSections> <add name=“connectionStrings”
provider=“RSAProtectedConfigurationProvider” /> </protectedDataSections></protectedData>
Async Methods Requires Async attribute on connection
string Limited to non-query command Reader or XmlReader
Begin/End ExecuteNonQuery ExecuteReader ExecuteXmlReader
3 Patterns for Async Implementation
// Start a non-blocking executionIAsyncResult iar =
cmd.BeginExecuteReader();
// Do work while command running ….
// Block the execution until doneSqlDataReader reader =
cmd.EndExecuteReader(iar);
// Process data hereWorkWithData(reader);
// Start a non-blocking executionIAsyncResult iar = cmd.BeginExecuteReader();
do {
// Do work while command running ….} while (!iar.IsComleted);
// Sync up and process dataSqlDataReader reader =
cmd.EndExecuteReader(iar);
// Process data hereWorkWithData(reader);
// Start a non-blocking executionIAsyncResult iar = cmd.BeginExecuteReader( new
AsyncCallback(WorkWithData),cmd);
// … later in your code
Public void WorkWithData(IAsyncResult ar){
// Retrieve the context of the callSqlCommand cmd = (SqlCommand) ar.AsyncState;
// Complete the async operationSqlDataReader reader = cmd.EndExecuteReader(ar);
}
Supports Dispose PatternDetermines if local or distributed
transaction are neededObjects that support ITransaction
can participate
using (TransactionScope ts = new System.Transactions.TransactionScope()) { bool success = true;
using (SqlConnection conn = new SqlConnection(ConnString)) { SqlCommand cmd = new SqlCommand(UpdateCmd, conn); cmd.Connection.Open(); try { cmd.ExecuteNonQuery(); } catch (SqlException ex) { // Error handling code goes here lblMessage.Text = ex.Message; success = false; } }
// Must call to complete; otherwise abort if(success)
ts.Complete(); }
New Properties AcceptChangesDuringUpdate FillLoadOption▪ OverwriteChanges (Current and Orginal)▪ PreserveChanges (Original Only)▪ Upsert (Current Version of row)
ReturnProviderSpecificTypes UpdateBatchSize
New Properties RemotingFormat▪ Binary or Xml
SchemaSerializationMode (IncludeShema/ExcludeSchema)
New Methods CreateDataReader – Creates a reader off
a Data Table
DataSet data = new DataSet();SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT * FROM employees;SELECT * FROM customers",
ConfigurationManager.ConnectionStrings["LocalNWind"].ConnectionString);adapter.Fill(data);
// Access the whole data set record by recordDataTableReader reader = data.CreateDataReader();
do{
while (reader.Read())Response.Write(String.Format("{0} <br>",
reader[1]));
Response.Write("<hr>");} while (reader.NextResult());
reader.Close();
New Data Source PropertiesBinding ExpressionsData Source Controls
DataSourceIDAppendDataBoundItems
DataBinder.Eval Can be used anywhere
Eval (shortcut for DataBinder.Eval) Can be used in the context of a data
bound control <%# Eval(“lastName”)%>
XPathBinder.Eval Used with Xml data anywhere
Xpath (shortcut for XPathBinder.Eval) Can be used in the context of a data bound
control <%#
Xpath(“Orders/Order/Customer/LastName”)%> XPathBinder.Select
Returns a nodeset that can be assigned to bound controls Data Source
DataSource=‘<%# XPathSelect(“orders/order/summary”)%>
Bind Method <asp:TextBox …. Text=‘<%#
Bind(“notes”)%> Two-Way Binding
Dynamic Expressions Evaluated when page compiles <%$ AppSettings:AppVersionNumber %> <%$ Resources:Resource, helloString%> <%$ ConnectionString:localNWind%>
Tabular Data Source Controls AccessDataSource ObjectDataSource SqlDataSource
Hierarchical Data Source Controls SiteMapDataSource XmlDataSource
DataSourceView
Properties for all of the actions (Delete,Insert,Update,Select) Command Parameters CommandType
FilterExpression / FilterParameters (only works with DataSet set for the DataSourceMode)
DataSourceMode Determines how data is returned
(DataSet or DataReader)CancelSelectOnNull
Canceled data retrieval if parameter is null
Command contain own set of parameters
Declarative Parameters ControlParameter CookieParameter FormParameter ProfileParameter QueryStringParameter SessionParameter
Caching Behavior CacheDuration (seconds) CacheExpirationPolicy (absolute,sliding) CacheKeyDependency (expiring the key) SqlCacheDependency (table dependent)
Created with each distinct SelectCommand, ConnectionString and SelectParameters
Async Features of ADO.NET can help in some situations
ConnectionString buildersNew TransactionScope simplifies
transactionsBinding Expressions simplify page
developmentNew DataSource objects simplify
binding to Sql Server and Objects
More info on InterKnowlogy:www.InterKnowlogy.com
Contact InformationE-mail: [email protected]: 760-930-0075 x274Blog: http://blogs.InterKnowlogy.com/AdamCalderon
About Adam Calderon Microsoft MVP – C# Microsoft UI Server Frameworks Advisory Council Developer / Author / Speaker / Teacher