ADO.NET Tips and Tricks How to get the most out of your data access…

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

Chapter 10 ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a programming interface to access data in a database.
Introduction to Database Processing with ADO.NET.
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
ADO. NET. What is “ADO.Net”? ADO.Net is a new object model for dealing with databases in.Net. Although some of the concepts are similar to the classical.
.NET Mobile Application Development Data in Distributed Systems Accessing Data with.NET.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Programming in ADO.NET: Data-Centric Applications and ADO.NET Original copyright by Microsoft, 2002, with minor modifications by Dan Eaves, 2005.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Mobile Data with the Compact Framework Shawn Wildermuth Senior Consultant/Architect Magenic Technologies Shawn Wildermuth Senior Consultant/Architect Magenic.
Object Oriented Databases by Adam Stevenson. Object Databases Became commercially popular in mid 1990’s Became commercially popular in mid 1990’s You.
Overview of Microsoft.Net and Vb.Net ITSE 2349 Spring 2002 Material from Microsoft.Net an Overview for ACC faculty by Stuart Laughton and Introduction.
Computer Science 317 Database Management Introduction to Web Access to Databases.
ADO.NET – part II August 2004 [ Marmagna Desai]. CONTENTS ADO vs ADO.NET ADO.NET – Managed providers Connecting to Database SqlConnection Selecting Database.
CNUG Day of.NET: October 30th SQL Server 2005: A Developers Introduction Shawn Wildermuth Magenic Technologies, Inc.
Visual Studio ®.NET Data with XML Carlotta Eaton ( Associate Professor of IST New River Community College Slides by Microsoft Modified.
DAT336 Connected vs Disconnected Data Access in ADO.NET Pablo Castro Program Manager – ADO.NET Team Microsoft Corporation.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
Overview of ADO.NET with the.NET Framework Scalable Development, Inc. Building systems today that perform tomorrow.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
.Net and Web Services Security CS795. Web Services A web application Does not have a user interface (as a traditional web application); instead, it exposes.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with Disconnected Data The DataSet and SqlDataAdapter ADO.NET - Lesson.
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
ASP.NET Rina Zviel-Girshin Lecture 5
Module 7: Accessing Data by Using ADO.NET
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Introduction to ADO.NET ADO.NET - Lesson 01  Training time: 10 minutes  Author:
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
ADO.NET Tips and Tricks How to get the most out of your data access…
ADO.NET connections1 Connecting to SQL Server and Oracle.
C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
Database Farming For Improved Performance Presented By: Russell Yong Supervisor: Prof Wentworth.
Why ADO.NET Not your father’s Data Access.
The Problems HTTP is disconnected So many database vendors Create a simple consistent versatile interface on the data Look at ADO.NET classes OleDb SQL.
DEV383 The ADO.NET DataSet and You Jackie Goldstein General Manager Renaissance Computer Systems
DAT430 Extending Microsoft ® ADO.NET Building a Custom Data Factory API DAT430 Extending Microsoft ® ADO.NET Building a Custom Data Factory API Gert E.R.
Why ADO.NET Not your father’s Data Access.
ADO.NET in Action Promises Realized.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
Module 3: Working with Local Data. Overview Using DataSets Using XML Using SQL Server CE.
SQL Server 2005: Extending the Type System with XML.
HNDIT Rapid Application Development
DataSets Demystified. Who I am Shawn Wildermuth Senior Consultant with Magenic Technologies ( C# MVP INETA.
C# .NET Software Development
1.NET Web Forms Applications: Main Form © 2002 by Jerry Post.
Introduction to ADO.Net Malek Kemmou CEO Arrabeta
Module 2: Using ADO.NET to Access Data. Overview ADO.NET Architecture Creating an Application That Uses ADO.NET to Access Data Changing Database Records.
Data Access. ADO.NET ADO.NET is the primary library for building database solutions within the.NET Framework. ADO.NET does not replace ADO. ADO and OLEDB.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
.NET Data Access and Manipulation
DAT 390 Advanced ADO.NET Programming Techniques Jackie Goldstein Renaissance Computer Systems
 ADO.NET is an object-oriented set of libraries that allows you to interact with data sources  Commonly, the data source is a database, but it could.
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
Programming the Web Using ASP.Net
Chris Menegay Sr. Consultant TECHSYS Business Solutions
Active Data Objects Binding ASP.NET Controls to Data
Chapter 10 ADO.
Active Data Objects Binding ASP.NET Controls to Data
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Introduction to Database Programming through ADO. NET
Presentation transcript:

ADO.NET Tips and Tricks How to get the most out of your data access…

Who I Am Shawn Wildermuth Independent Consultant ( C# MVP MCSD.NET INETA Speaker Book Author – “Pragmatic ADO.NET” Editor of This Presentation can be found at: – Shawn Wildermuth Independent Consultant ( C# MVP MCSD.NET INETA Speaker Book Author – “Pragmatic ADO.NET” Editor of This Presentation can be found at: –

Overview Can you do ADO.NET Wrong? Unmanaged Resources Connections DataSets Typed DataSets CommandBuilders DataAdapters DataSets & ASP.NET Distributed DataSets Transactions Vendor Neutral Code Can you do ADO.NET Wrong? Unmanaged Resources Connections DataSets Typed DataSets CommandBuilders DataAdapters DataSets & ASP.NET Distributed DataSets Transactions Vendor Neutral Code

Are You Doing Anything Wrong? Can you write bad ADO.NET Code? Yes…but: – It is usually intuitive about what is right – Disconnected nature makes it harder to break Areas of confusion about ADO.NET – Easier to scale, but not fool-proof – Disconnected does not mean scalable – Concurrency is harder than older systems  (e.g. ADO) – “Why Can’t I Lock Rows” Can you write bad ADO.NET Code? Yes…but: – It is usually intuitive about what is right – Disconnected nature makes it harder to break Areas of confusion about ADO.NET – Easier to scale, but not fool-proof – Disconnected does not mean scalable – Concurrency is harder than older systems  (e.g. ADO) – “Why Can’t I Lock Rows”

Unmanaged Resources Most ADO.NET objects are IDisposable – Make sure and Dispose() – Inheritance from Component means Dispose() – Not disposing objects will cause leaky code Most ADO.NET objects are IDisposable – Make sure and Dispose() – Inheritance from Component means Dispose() – Not disposing objects will cause leaky code Dim conn As New SqlConnection("...") Dim cmd As SqlCommand = conn.CreateCommand() cmd.CommandText = "..." conn.Open() Dim rdr As SqlDataReader = cmd.ExecuteReader() While rdr.Read() Console.WriteLine(rdr.GetString(0)) End While conn.Close() ' potential leaky code even though you closed the connection!

Unmanaged Resources (3) Use Try…Finally – No “using” in VB.NET, so must do it all in finally – Ensures always disposed, even if exception Use Try…Finally – No “using” in VB.NET, so must do it all in finally – Ensures always disposed, even if exception Dim conn as new SqlConnection("...") Dim cmd as SqlCommand = conn.CreateConnection Try cmd.CommandText = "..." conn.Open() Dim rdr as SqlDataReader = cmd.ExecuteReader() While rdr.Read() = True Console.WriteLine(rdr.GetString(0)) End While Finally ' Clean Up conn.Close() rdr.Dispose() cmd.Dispose() conn.Dispose() End Try

Connections Connections are precious – In DataReaders, let it close it when it is done: Connections are precious – In DataReaders, let it close it when it is done: Try conn.Open() Dim rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While rdr.Read() ' Closes Here on last read Console.WriteLine(rdr.GetString(0)) End While Finally ' Make sure we didn’t throw an exception and leak a connection conn.Close() End Try

Connections (2) Connections are still precious – With DataSets, never open them: Connections are still precious – With DataSets, never open them: Dim ds As New DataSet Dim conn As New SqlConnection("...") Dim adapter As New SqlDataAdapter("...") ' The adapter will always preserve the state ' of the connection during the fill ' No Need to Open Or Close the connection because the adapter will ' close it as soon as possible since it is already closed adapter.Fill(ds) ' If it is open, it will leave it open conn.Open() adapter.Fill(ds) conn.Close()

Connections (3) Don’t Hardcode Connection Strings – VS.NET Designer Does it Wrong – Store Them in.Config Files Don’t Hardcode Connection Strings – VS.NET Designer Does it Wrong – Store Them in.Config Files <add key="SqlConnString" value="Server=localhost;Database=Northwind;..." /> <add key="SqlConnString" value="E234998F98A98F..." />

Connections (4) Use Connection Factories – Isolates Connection String Storage – Increases Security by Controlling Access Use Connection Factories – Isolates Connection String Storage – Increases Security by Controlling Access Public Class ConnectionStrings Public Shared Function GetConnection() _ As OleDbConnection return new OleDbConnection( _ ConfigurationSettings.AppSettings("ConnString")) End Function End Class

Connections (5) Secure Connection Strings with Encryption – You could write your own Encryption Library – Better would be if MS supplied one  In Windows 2000 and later, use DPAPI  DPAPI Eliminates the Key Management Problem  Encrypts on a Per Machine or Per User Basis  Caveat: May Require Encrypting on Every Machine Described in Detail in a Microsoft PAP: – Secure Connection Strings with Encryption – You could write your own Encryption Library – Better would be if MS supplied one  In Windows 2000 and later, use DPAPI  DPAPI Eliminates the Key Management Problem  Encrypts on a Per Machine or Per User Basis  Caveat: May Require Encrypting on Every Machine Described in Detail in a Microsoft PAP: –

DataSets DataSets have full database schema – Tables – Columns – Primary and Foreign Keys – Constraints – Even Triggers Using Full Schema – Allows validation without a network roundtrip – Relationships allows hierarchical view of data DataSets have full database schema – Tables – Columns – Primary and Foreign Keys – Constraints – Even Triggers Using Full Schema – Allows validation without a network roundtrip – Relationships allows hierarchical view of data

DataSets (2) Use DataSets for data caching – Most data is not volatile – Saves roundtrips to the database – Less code than writing custom classes Use DataSets for data caching – Most data is not volatile – Saves roundtrips to the database – Less code than writing custom classes Public Class _default Inherits Page Dim _dataSet As DataSet Const MYDATASET As String = "MYDATASET" Sub OnLoad(...) If Session(MYDATASET) Is Nothing Then _dataSet = New DataSet Else _dataSet = DirectCast(Session(MYDATASET), DataSet) End If '... Session(MYDATASET) = _dataSet End Sub End Class

DataSets (3) DataSets can incrementally grow – DataAdapter.Fill adds to DataSet, not replace – Allows cache to be built up as needed DataSets can incrementally grow – DataAdapter.Fill adds to DataSet, not replace – Allows cache to be built up as needed ' Fill DataSet with Product #1 = 1 adapter.Fill(_dataSet) '... ' Fill DataSet with Product #2 = 2 adapter.Fill(_dataSet) ' Now DataSet has both products in, not just one or the other

DataSets (4) Use DataSets for intermittent connectivity – Store locally between times of connectivity – Stored DataSets preserve state of changes – Great for mobile apps (not just CF) Use DataSets for intermittent connectivity – Store locally between times of connectivity – Stored DataSets preserve state of changes – Great for mobile apps (not just CF) Public Class MainForm Inherits Form Dim _dataSet as DataSet Sub OnClose(...) _dataSet.WriteXml("foo.xml", XmlWriteMode.DiffGram) End Sub Sub OnLoad(...) _dataSet.ReadXml("foo.xml", XmlReadMode.DiffGram) End Sub End Class

Typed DataSets Use Typed DataSets for Stable Schemas – Data Validate at Compile Time – Improves Developer Productivity with Intellisense – Easier to maintain in light of schema changes than code – Loads XSD Schema in with Code (faster) – Demo Use Typed DataSets for Stable Schemas – Data Validate at Compile Time – Improves Developer Productivity with Intellisense – Easier to maintain in light of schema changes than code – Loads XSD Schema in with Code (faster) – Demo

CommandBuilders Good for Simple Optimistic Concurrency – Concurrency based on original values – Robust, but Inefficient – Update and Deletes are huge – No support for Stored Procedures Good for Simple Optimistic Concurrency – Concurrency based on original values – Robust, but Inefficient – Update and Deletes are huge – No support for Stored Procedures DELETE FROM CUSTOMER WHERE ( (CustomerID AND ((FirstName IS NULL IS NULL) OR (FirstName AND ((LastName IS NULL IS NULL) OR (LastName AND ((MiddleName IS NULL IS NULL) OR (MiddleName AND ((Address IS NULL IS NULL) OR (Address AND ((Apartment IS NULL IS NULL) OR (Apartment AND ((City IS NULL IS NULL) OR (City AND ((State IS NULL IS NULL) OR (State AND ((Zip IS NULL IS NULL) OR (Zip AND ((HomePhone IS NULL IS NULL) OR (HomePhone AND ((BusinessPhone IS NULL IS NULL) OR (BusinessPhone AND ((DOB IS NULL IS NULL) OR (DOB AND ((Discount IS NULL IS NULL) OR (Discount AND ((CheckedOut IS NULL IS NULL) OR (CheckedOut )

CommandBuilders (2) Conclusion – Great for Prototyping – Bad for Production Code – Designer can achieve same at compile time Conclusion – Great for Prototyping – Bad for Production Code – Designer can achieve same at compile time

DataAdapters Use different adapters to load and update – Batch Adapters to load multiple tables – Single table adapters to update tables Use Designer Support – Add a Component to project to hold Adapters – Use designer to create Mappings – Get CommandBuilder Behavior at Compile-time – Or Map to Stored Procedures (preferred) Demo Use different adapters to load and update – Batch Adapters to load multiple tables – Single table adapters to update tables Use Designer Support – Add a Component to project to hold Adapters – Use designer to create Mappings – Get CommandBuilder Behavior at Compile-time – Or Map to Stored Procedures (preferred) Demo

DataSets & ASP.NET Cache DataSets for non-volatile data – 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 Cache DataSets for non-volatile data – 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 Public Class _default Inherits Page Dim _dataSet As DataSet Const MYDATASET As String = "MYDATASET" Sub OnLoad(...) If Session(MYDATASET) Is Nothing Then _dataSet = New DataSet Else _dataSet = DirectCast(Session(MYDATASET), DataSet) End If '... Session(MYDATASET) = _dataSet End Sub End Class

DataSets and ASP.NET (2) “What caching should I use?” – Session for user specific data  E.g. User preferences, shopping cart, etc. – Application for app-level data  E.g. e-commerce catalog, historical data, etc. – Cache objects for volatile data  E.g. stock prices, weather data, etc. “What caching should I use?” – Session for user specific data  E.g. User preferences, shopping cart, etc. – Application for app-level data  E.g. e-commerce catalog, historical data, etc. – Cache objects for volatile data  E.g. stock prices, weather data, etc.

Distributed DataSets Treat DataSets as messages – Same in Remoting DataSets as Web Services – Remote the factory that delivers DataSets – When updating, only return changes – Minimize the data across the wire with Merge Treat DataSets as messages – Same in Remoting DataSets as Web Services – Remote the factory that delivers DataSets – When updating, only return changes – Minimize the data across the wire with Merge Class DataSetFactory 'Remoted Class ' Remotely returns the DataSet Public Function GetData() as DataSet '... End Function Public Function SaveChanges(ByVal ds as DataSet) as DataSet '... End Function End Class Dim newDS as DataSet = factory.SaveChanges(ds.GetChanges()) ds.Merge(newDs)

Distributed DataSets (2) Is fine to use DataSets in Web Services – Default serialization is incorrect  DiffGram Format is Platform Specific – You must make it an XML Document manually  Can use GetXml() or XmlDataDocument Is fine to use DataSets in Web Services – Default serialization is incorrect  DiffGram Format is Platform Specific – You must make it an XML Document manually  Can use GetXml() or XmlDataDocument _ Public Function GetData() as XmlDocument Dim ds as new DataSet() ' Fill the DataSet return new XmlDataDocument(ds) End Function

Distributed DataSets (3) Typed DataSets are great in Web Services – Can refer to.xsd in hand-coded WSDL – While allowed, some toolkits don’t support it – No way to make ?wsdl do it (at least not yet) Typed DataSets are great in Web Services – Can refer to.xsd in hand-coded WSDL – While allowed, some toolkits don’t support it – No way to make ?wsdl do it (at least not yet) <definitions... xmlns:tds="

Distributed DataSets (4) Remoting may not work as expected – DataSets Remoted by Value  DataSet derive from MarshalByValueComponent  So always remoted by value! – Remoting DataTables/Rows does not help  References to part of DataSet data transmit entire DataSet – Remoting DataSets can work  Must transmit XML or subset of XML (of the DataSet) Remoting may not work as expected – DataSets Remoted by Value  DataSet derive from MarshalByValueComponent  So always remoted by value! – Remoting DataTables/Rows does not help  References to part of DataSet data transmit entire DataSet – Remoting DataSets can work  Must transmit XML or subset of XML (of the DataSet)

Transactions Server Transactions are usually preferable – Generally shorter, therefore better – Server Tx allows results to be returned – Server Tx are not server cursors Server Transactions are usually preferable – Generally shorter, therefore better – Server Tx allows results to be returned – Server Tx are not server cursors

Transactions (2) Client Transactions Have their Place – Allows a client lock of rows (connected model) – Connection must be maintained for length of Tx – Be careful when using them for locking  Scalability and performance will suffer  Must have recovery mechanism Client Transactions Have their Place – Allows a client lock of rows (connected model) – Connection must be maintained for length of Tx – Be careful when using them for locking  Scalability and performance will suffer  Must have recovery mechanism

Transactions (3) Dim tx As SqlTransaction Dim cmd As SqlCommand Dim rdr As SqlDataReader Try conn.Open() tx = conn.BeginTransaction() ' Get some Data cmd = conn.CreateCommand() cmd.CommandText = "SELECT * FROM Authors WHERE au_id = ' '" cmd.Transaction = tx ' Don’t forget to set the transaction into the cmd rdr = cmd.ExecuteReader() ' Get the zip and close the reader rdr.Read() Dim zip As String = rdr("zip").ToString() rdr.Close() ' Make a change cmd.CommandText = "UPDATE authors SET zip = ‘12345’" cmd.ExecuteNonQuery() ' Commit the Tx tx.Commit() Catch tx.Rollback() Finally cmd.Dispose() rdr.Dispose() conn.Close() conn.Dispose() End Try

Should You Write Vendor Neutral Code? The Promise of Vendor Neutral SQL is wrong – Tuning databases too important – Standard SQL isn’t complete – Only do it if you have a compelling need You can get half the promise – Write your ADO.NET in a vendor neutral way – You may need to port the back-end code – Saves you from rewriting it all The Promise of Vendor Neutral SQL is wrong – Tuning databases too important – Standard SQL isn’t complete – Only do it if you have a compelling need You can get half the promise – Write your ADO.NET in a vendor neutral way – You may need to port the back-end code – Saves you from rewriting it all

Using Vendor Neutral Code Interfaces are key – IDbConnection is a great place to start – Connection Factory to return IDbConnection – Commands: IDbConnection.CreateCommand() – Readers: IDbCommand.ExecuteReader() Interfaces are key – IDbConnection is a great place to start – Connection Factory to return IDbConnection – Commands: IDbConnection.CreateCommand() – Readers: IDbCommand.ExecuteReader() Sub GetReader(SQL as String) as IDataReader ' Connection String Factory Dim conn as IDbConnection = ConnectionStrings.GetConnection() ' Follow the Rest of the model Dim cmd as IDbCommand = conn.CreateCommand() cmd.CommandText = SQL Dim reader as IDataReader = cmd.ExecuteReader() return reader End Sub

Using Vendor Neutral Code (2) Works with DataAdapters too (mostly) – IDbConnection is a still a great place to start – No Factory for Data Adapters unfortunately – Can use the connection to create the command Works with DataAdapters too (mostly) – IDbConnection is a still a great place to start – No Factory for Data Adapters unfortunately – Can use the connection to create the command Sub GetAdapter(SQL as String) as IDbDataAdapter ' Connection String Factory Dim conn as IDbConnection = ConnectionStrings.GetConnection() ' Create the DataAdapter Dim adapter as new SqlDataAdapter() ' Follow the Rest of the model adapter.SelectCommand = conn.CreateCommand() adapter.SelectCommand.CommandText = SQL return adapter }

Using Vendor Neutral Code (3) Vendor Specific Features – Can cast to get specific features of an engine – The more you do, the less vendor neutral it is – This should be the exception, not the rule Vendor Specific Features – Can cast to get specific features of an engine – The more you do, the less vendor neutral it is – This should be the exception, not the rule Dim cmd as IDbCommand = GetCommand("SELECT * FROM AUTHORS FOR XML;") If cmd is SqlCommand Then Dim sqlCmd as SqlCommand = DirectCast(cmd, SqlCommand) Dim xmlReader as XmlReader = sqlCmd.ExecuteXmlReader() End If

Conclusion You can write ADO.NET badly Bad ADO.NET not nearly as toxic as bad ADO DataSets are your friend…really Relationship of DataSets and XSD is good Distributed DataSets are not that hard CommandBuilders are vaguely evil You can write ADO.NET badly Bad ADO.NET not nearly as toxic as bad ADO DataSets are your friend…really Relationship of DataSets and XSD is good Distributed DataSets are not that hard CommandBuilders are vaguely evil

Questions?