Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

30
DataBinding in ASP.NET 2.0 Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy

Transcript of Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Page 1: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

DataBinding in ASP.NET 2.0

Adam Calderon – C# MVPApplication Development Practice LeadInterKnowlogy

Page 2: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Agenda

ADO.NET New Features Binding Model Changes

Page 3: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features

DbProviderFactories SqlConnection Web.config SqlCommand TransactionScope SqlDataAdaptor DataSet

Page 4: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features - DbProviderFactory

CreateCommand CreateCommandBuilder CreateConnection CreateDataAdaptor CreateParameter

Page 5: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – DbProviderFactory Sample

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

Page 6: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – SqlConnection

Asynchronous Operation Support Failover Partner MultipleActiveResultSets (MARS) Connection String Builders

Page 7: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – Web.config

ConnectionStrings elementConfigurationManager.ConnectionStrings[“MySql”].ConnectionStri

ng

Protecting Connection Strings Use aspnet_regiis.exe to encrypt

web.config <protectedData>

<protectedDataSections> <add name=“connectionStrings”

provider=“RSAProtectedConfigurationProvider” />

</protectedDataSections></protectedData>

Page 8: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – SqlCommand

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

Page 9: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – SqlCommand Async Patterns (1)

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

Page 10: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – SqlCommand Async Patterns (2)

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

Page 11: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – SqlCommand Async Patterns (3)

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

}

Page 12: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – TransactionScope

Supports Dispose Pattern Determines if local or distributed

transaction are needed Objects that support ITransaction can

participate

Page 13: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – TransactionScope

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

Page 14: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features - SqlDataAdaptor

New Properties AcceptChangesDuringUpdate FillLoadOption▪ OverwriteChanges (Current and Orginal)▪ PreserveChanges (Original Only)▪ Upsert (Current Version of row)

ReturnProviderSpecificTypes UpdateBatchSize

Page 15: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features - DataSet

New Properties RemotingFormat▪ Binary or Xml

SchemaSerializationMode (IncludeShema/ExcludeSchema)

New Methods CreateDataReader – Creates a reader off

a Data Table

Page 16: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features – DataSet CreateDataReader

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

Page 17: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

ADO.NET New Features

Page 18: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes

New Data Source Properties Binding Expressions Data Source Controls

Page 19: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – New Data Source Properties

DataSourceID AppendDataBoundItems

Page 20: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Binding Expressions (1)

DataBinder.Eval Can be used anywhere

Eval (shortcut for DataBinder.Eval) Can be used in the context of a data

bound control <%# Eval(“lastName”)%>

Page 21: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Binding Expressions (2)

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”)%>

Page 22: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Binding Expressions (3)

Bind Method <asp:TextBox …. Text=‘<%#

Bind(“notes”)%> Two-Way Binding

Dynamic Expressions Evaluated when page compiles <%$ AppSettings:AppVersionNumber %> <%$ Resources:Resource, helloString%> <%$ ConnectionString:localNWind%>

Page 23: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Data Source Controls

Tabular Data Source Controls AccessDataSource ObjectDataSource SqlDataSource

Hierarchical Data Source Controls SiteMapDataSource XmlDataSource

DataSourceView

Page 24: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Data Source Controls – SqlDataSource (1)

Properties for all of the actions (Delete,Insert,Update,Select) Command Parameters CommandType

FilterExpression / FilterParameters (only works with DataSet set for the DataSourceMode)

Page 25: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Data Source Controls – SqlDataSource (2)

DataSourceMode Determines how data is returned

(DataSet or DataReader) CancelSelectOnNull

Canceled data retrieval if parameter is null

Page 26: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Data Source Controls – SqlDataSource (3)

Command contain own set of parameters

Declarative Parameters ControlParameter CookieParameter FormParameter ProfileParameter QueryStringParameter SessionParameter

Page 27: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes – Data Source Controls – SqlDataSource (4)

Caching Behavior CacheDuration (seconds) CacheExpirationPolicy (absolute,sliding) CacheKeyDependency (expiring the key) SqlCacheDependency (table dependent)

Created with each distinct SelectCommand, ConnectionString and SelectParameters

Page 28: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Binding Model Changes

Page 29: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Session Summary

Async Features of ADO.NET can help in some situations

ConnectionString builders New TransactionScope simplifies

transactions Binding Expressions simplify page

development New DataSource objects simplify

binding to Sql Server and Objects

Page 30: Adam Calderon – C# MVP Application Development Practice Lead InterKnowlogy.

Adam Calderon

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