overview of ado.net with the.net framework scalable development, inc. building systems today that...
TRANSCRIPT
Overview of ADO.NETwith the .NET Framework
Scalable Development, Inc.Building systems today that perform tomorrow.
.NET Experiences
PDC 2000 Build (July 2000). Visual Studio 1.0 Beta 1 (November 2000). Book began (January 2001). Visual Studio 1.0 Beta 2 (June 2001). First Production ASP.NET App (July 2001). Production Windows Service (November 2001).
Runs today. 4 Production Applications by shipment. Multiple running applications.
.NET Resources
ASP.NET – www.asp.net AspAdvice – www.aspadvice.com Windows Forms – www.windowsforms.net Architecture –
msdn.microsoft.com/architecture .NET News – www.dotnetwire.com
Agenda
Design PhilosophyArchitectural OverviewFeaturesWhen to use What (Code Examples)Summary
Design Philosophy Unified Data Story (data, xml, cache objects)
Data is Data; object model is choice XML objects feel like XML, Data objects feel like Data,
Typed Objects feel like objects Factored components
Explicit model; no black boxes! (Customers/helper code wires together components)
Predictable behaviour, semantics Optimized performance
Disconnected Relational DataSet Get Data as fast as possible
Managed Data Overview
What Happenedto My RecordSet?
RecordSet Updateable? Scrollable? Bookmarks? Rowcount?
Holding server resources? Cache on client?
DataReader Connected, non-cached, FO/RO RecordSet
DataSet Disconnected, cached, scrollable data
DataAdapter Logic for populating the DataSet and propagating
changes back to the datasource
Managed Providers Manages interaction to a data source
Managed equivalent of OLE DB layer Directly exposes consumer interfaces Not a full featured data store interface Specific to (Optimized for) DataSource
Managed Provider Object Model Connection
Like ADODB.Connection Command
Like ADODB.Command DataReader
Similar to FO/RO ADODB.RecordSet Fields accessed through strongly typed, indexed accessors
Database Support
System.Data.SQLClient SQL Server 7 SQL Server 2000
Oracle.DataAccess (ODP.NET). System.Data.Oracle (MS). DB2 (only supports .NET 1.0). MySql. System.Data.OleDb System.Data.Odbc ODBC drivers.
Oracle Managed Providers
Microsoft. No support for COM+.
Oracle. Requires Oracle 9iR2 client.
Oracle Support Through OleDb
Microsoft Driver for Oracle. (MsDaOra)7.x datatypes.No 8.x datatypes.
Oracle OleDb Driver. (OraOleDb.Oracle)7.x datatypes.8.x datatypes.9.x datatypes.COM+ challenged.
Oracle Support Through ODBC
Microsoft Driver for Oracle.
Oracle ODBC driver.Thread challenged.
Oracle Gotchas
Use the latest Oracle SQL Net.
Don’t use COM+ transactions, unless youneed them. Info - Oracle is working on an OleDb driver that supports COM+transactions better.
Always close connections!!!!!!
DataSet Common client data store
Relational View of Data Tables, Columns,
Rows, Constraints, Relations
Directly create metadata and insert data
DataSetDataSetTablesTables
TableTable
ColumnsColumnsColumnColumn
ConstraintsConstraintsConstraintConstraint
RowsRowsRowRow
RelationsRelationsRelationRelation
DataSet Common client data store
Explicit Disconnected Model Disconnected, remotable object No knowledge of data source or properties
Common BehaviourPredictable performance characteristics
Strong Typing 3-D Collection What to return from a DAL. Uses DataReader underneath the covers. Some column metadata is not available.
Data Adapter Loads a table from a data store and
writes changes back. Exposes two important methods:
Fill(DataSet,DataTable)Update(DataSet,DataTable)
Provides mappings between tables & columns User provides insert/update/delete commands
Allows use of Stored ProceduresCommandBuilder component available (not
used much in ASP.NET) Allows single DataSet to be populated from multiple
different datasources
ADO.NET and XML
The DataSet Loads/saves XML data into/out of DataSet Schema can be loaded/saved as XSD Schema can be inferred from XML Data
The DataSet can be associated with an XmlDataDocument Exposes a relational view over structured XML
According to the DataSet schema Allows strong typing, control binding, relational access of
XML data Allows XML tools (schema validation, XSL/T, XPath queries)
against relational data Preserves full fidelity of XML Document
When to use What Connected Data Access
Code Examples:Retrieving ResultsInsert, Update, and
Delete. Disconnected Data Access
Code Examples:Application DataLoading XMLClient Cursor Updating
XML View of Relational Data Code Example:
SQLXMLXML Manipulations
Connected Data Access Connected Data Access - Managed Providers
Connection, TransactionConnecting to DataSourceStarting/Ending Transactions
Command, ParametersDatabase Updates, Selects, DDL
DataReader(FO/RO) Server Cursor
DataAdapterPushing data into DatasetReading changes out of DataSet
Code: Retrieving Results
‘Create and open an OleDbConnectionDim OleDbCn as new OleDbConnection(“……”)OleDbCn.Open()
‘Create and execute OleDbCommandDim OleDbCmd as new OleDbCommand("Select * from authors where ...", OleDbCn)Dim dr as DataReaderdr = OleDbCmd.ExecuteReader()
‘Retrieve Resultswhile(dr.Read())
Console.WriteLine("Name = " + dr("au_lname“))End whiledr.Close()OleDbCn.Close() ‘This is VERY IMPORTANT
Disconnected Data Access
Disconnected Data Access - DataSet Application Data Remoting Results
SOAP, WebMethods, Remoting Caching Results
ASP.NET Cache Persisting results
Save Data as XML, Schema as XSD User interaction
Scrolling, sorting, filtering DataView, DataViewManager
Binding Windows controls
Code: Application Data
‘ Create an "Inventory" TableDim ds as new DataSet() Dim inventory as new DataTable("Inventory")inventory.Columns.Add("TitleID",typeof(Int32))inventory.Columns.Add("Quantity",typeof(Int32))ds.Tables.Add(inventory)
‘ Add a record to the Inventory tableDim row as inventory.NewRow()Row("TitleID“)=1Row("Quantity“)=25inventory.Rows.Add(row)
Code: Loading XML
‘Load DataSet with XMLDim ds as new DataSet()ds.ReadXml("inventory.xml")
‘Add a record to the Inventory tableDim inventory as new DataTable = ds.Tables("Inventory“)Dim row as DataRow = inventory.NewRow()Row("TitleID“)=1Row("Quantity“)=25inventory.Rows.Add(row)
‘Write out XMLds.WriteXml("updatedinventory.xml")
Code: Insert/Update/Delete
Dim OleDbCn as new OleDbConnection(“…….”)Dim OleDbCM as new OleDbCommand(
“Insert/Update/Delete Command“, OleDbCn)OleDbCn.Open()OleDbCm.ExecuteNonQuery()If OleDbCn.State <> ConnectionState.StateClosed then
OleDbCn.Close()End ifOleDbCn = Nothing ‘Old habits die hard
Code: Client Cursor Updating (easy)
‘Populate DataSetDim OleDbDA as new OleDbDataAdapter(
"Select * from customers“, OleDbCn);Dim ds as new Dataset() OleDbDA.MissingSchemaAction = MissingSchemaAction.AddWithKeyOleDbDA.Fill(ds, "Customer")
‘Find customer w/PK value of 256Dim dr as DataRow = ds.Tables("Customer“).Rows.Find(256)
‘Change LastNameDr("LastName“) = "Smith"
‘Update DataBaseDim OleDbCb as new OleDbCommandBuilder = OleDbCommandBuilder(da)OleDbDa.Update(ds, "Customer")
Code: Client Cursor Operations (harder)
‘Populate DataSetDim OleDbDA as new OleDbDataAdapter("Select customerId, customerName from customers“, OleDbCn);Dim ds as new Dataset() Dim dr as DataRow
OleDbDA.Fill(ds, "Customer")
OleDbDA.InsertCommand = new OleDbCommand(“insert into customers (CustomerName) values (@CustomerName)”, OleDbCn)
dr = ds.Tables(“Customer”).NewRow()‘Add Customer NameDr("Customer Name“) = "Fred's Company"
‘Update DataBaseds.Tables(“Customer”).Rows.Add(dr)OleDbDA.Update(ds, “Customer”)
Notes on the Client Cursor Update
Individual commands are sent.
Can be wrapped in a transaction.
CommandBuilder is “relatively” inefficient.
Code: Manual Transaction
Dim OleDbCM as new OleDbCommand(“Insert/Update/Delete Command“, OleDbCn)
Dim OleDbTx as OleDbTransactionOleDbTx = OleDbCn.BeginTransaction(Isolation.ReadUncommitted)OleDbCm.Transaction = OleDbTxTry
OleDbCn.Open()OleDbCm.ExecuteNonQuery()OleDbTx.Commit()
Catch exc as ExceptionOleDbTx.RollBack()Throw( new Exception( “Error Occurred”, exc.InnerException )
FinallyIf OleDbCn.State <> ConnectionState.StateClosed then
OleDbCn.Close()End ifEnd TryOleDbCn = Nothing
Cleanup
Close your connection objects and return them to the connection pool.
Dispose all objects. Don't wait on the finalizer.
Great, Now What’s Missing?
Server-side scrollable cursor support. (not an issue for Oracle)
Complete column information.
ADOX.Catalog type of support. No support for creating tables, columns, users, indexes, ……..
ADO Classic in .NET
Works.Can continue to use it.Required for ADOX support.
Summary
ADO.NET is… Optimized for Data Access.
Managed Providers for connected access
DataSet for disconnected, user interaction
DataReader for connected RO use. Open Architecture
No Black Boxes Tightly Integrated with XML
DataSet reads/writes XMLXmlDataDocument integrates relational
and XML views
Questions?
Scalable Development, Inc. Consulting & Development Services. http://www.scalabledevelopment.com 865-693-3004. [email protected]
END
Scalable Development, Inc.Building systems today that perform tomorrow.